Entity framework EF CTP 5创建和持久化对象图故障
代码: 运行时给我一个关于空引用的错误。 相关的是虚拟Icollection。 实体中未定义外键字段 相反,如果我这样做Entity framework EF CTP 5创建和持久化对象图故障,entity-framework,ef4-code-only,Entity Framework,Ef4 Code Only,代码: 运行时给我一个关于空引用的错误。 相关的是虚拟Icollection。 实体中未定义外键字段 相反,如果我这样做 Something smt = new Something(){ Prop = 123, Prop2 = "asdad" } foreach(var related in relatedsomething) { smt.Related.Add(new Related(){ relatedprop = 123, }; } 它起作用了。 尽管如此,我还
Something smt = new Something(){
Prop = 123,
Prop2 = "asdad"
}
foreach(var related in relatedsomething)
{
smt.Related.Add(new Related(){
relatedprop = 123,
};
}
它起作用了。尽管如此,我还是希望它能像第一段一样工作。
我做错什么了吗?”因为在EF4中,它是双向工作的 模型类别(相关部分):
公共类打印机
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共虚拟ICollection副本{get;set;}
}
公共类副本
{
公共int Id{get;set;}
公共虚拟打印机打印机{get;set;}
}
公共类PrinterContext:DbContext
{
公共数据库集打印机{get;set;}
公共数据库集副本{get;set;}
}
我想我可能遇到了同样的问题,但没有得到回应
这可能是EF中的一个bug,您必须与之共存并解决它。使用代码时,您必须首先在构造函数中启动集合
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; }
}
类打印机
{
公共虚拟ICollection副本{get;set;}
公用打印机{
副本=新的HashSet();
}
}
它会神奇地再次工作。请发布您的对象模型,包括一些东西和相关类。谢谢
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; }
}
class printer
{
public virtual ICollection<replica> replicas {get;set;}
public printer{
replicas = new HashSet<replica>();
}
}