代码:
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; }
}