【发布时间】:2012-02-26 03:59:09
【问题描述】:
代码:
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
};
}
它有效。
虽然,我希望它像第一个 sn-p 一样工作。
难道我做错了什么? '因为在交付的 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; }
}
【问题讨论】:
-
请发布您的对象模型,包括 Something 和 Related 类。谢谢。
标签: entity-framework ef4-code-only