0

代码:

Something smt = new Something(){
Prop = 123,
Prop2 = "asdad"
}

foreach(var related in relatedsomething)
{
    smt.Related.Add(new Related(){
    relatedprop = 123,
    };
}

运行时给我一个关于空引用的错误。相关的是虚拟Icollection。实体中没有定义外键字段。

相反,如果我这样做

foreach(var related in relatedsomething)
{
db.Related.Add(new Related(){
    relatedprop = 123,
    Something = smt
    };
}

有用。
虽然,我希望它像第一个片段一样工作。
难道我做错了什么?'因为在交付的 EF4 中它可以双向工作。

模型类(相关部分):

public class Printer
{
    public int Id { get; set; }
    public string  Name { get; set; }
    public virtual ICollection<Replica> Replicas { get; set; }


}
public class Replica
{
    public int Id { get; set; }
    public virtual Printer Printer { get; set; }


}


public class PrintersContext: DbContext
{
    public DbSet<Printer> Printers { get; set; }
    public DbSet<Replica> Replicas { get; set; }

}
4

2 回答 2

0

我想我可能遇到了同样的问题。我在 MSDN 上发帖,但没有得到回应。

这可能是 EF 中的一个错误,您必须忍受并解决它。

于 2010-12-21T16:33:01.007 回答
0

首先使用代码,您必须在构造函数中启动您的集合。

 class printer
 {
   public virtual ICollection<replica> replicas {get;set;}
    public printer{
      replicas = new HashSet<replica>();
    }
 }

它会再次神奇地工作。

于 2012-02-25T19:59:09.390 回答