EF CTP 5 创建和持久对象图问题
代码:
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; }
}
Code:
Something smt = new Something(){
Prop = 123,
Prop2 = "asdad"
}
foreach(var related in relatedsomething)
{
smt.Related.Add(new Related(){
relatedprop = 123,
};
}
Runtime gives me an error about null reference.
Related is virtual Icollection.
no foreign key fields in entities defined.
on contrary if I do
foreach(var related in relatedsomething)
{
db.Related.Add(new Related(){
relatedprop = 123,
Something = smt
};
}
It works.
Although, I Want it to work as in first snippet.
Am I doing something wrong? 'Cos in shipped EF4 it works both ways.
model classes (relevant part):
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; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先使用代码,您必须在构造函数中启动集合。
一切都会神奇地再次发挥作用。
With code first you got to initiate your collections in constructor.
and it'll all magically work again.
我想我可能也遇到了同样的问题。 我在 MSDN 上发布了,但没有得到任何回应。
这可能是 EF 中的一个错误,您必须忍受并解决它。
I think I might have run into the same problem. I posted on MSDN, but got no response.
It's probably a bug in EF, which you have to live with and work around.