如何防止 InvalidOperationException 保存实体的循环图?
给定实体,
class A {
B DefaultB { get; set; }
C DefaultC { get; set; }
}
class B {
A { get; set; }
}
class C {
A { get; set; }
}
其中 A.DefaultB
和 A.DefaultC
是可选的,
modelBuilder.Entity<A>().HasOptional(x => x.DefaultB).WithMany();
modelBuilder.Entity<A>().HasOptional(x => x.DefaultC).WithMany();
context.Set
和 context.SaveChanges()
可以保存以下对象图吗?
var b = new B();
var c = new C();
var a = new A { DefaultB = b, DefaultC = c, };
b.A = a;
c.A = a;
// now save these...
现在,我得到一个 InvalidOperationException
(迭代时的集合修改),因为 EF 似乎不能很好地处理循环。
Given the entities,
class A {
B DefaultB { get; set; }
C DefaultC { get; set; }
}
class B {
A { get; set; }
}
class C {
A { get; set; }
}
where A.DefaultB
and A.DefaultC
are optional,
modelBuilder.Entity<A>().HasOptional(x => x.DefaultB).WithMany();
modelBuilder.Entity<A>().HasOptional(x => x.DefaultC).WithMany();
what combination of context.Set<T>().Add(...)
and context.SaveChanges()
would work to save the following object graph?
var b = new B();
var c = new C();
var a = new A { DefaultB = b, DefaultC = c, };
b.A = a;
c.A = a;
// now save these...
As it is now, I get an InvalidOperationException
(collection modification while iterating) because EF does not seem to handle cycles very well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您好,您需要调整您的映射:
以及此映射的正确保存顺序:
Hi you need to adjust your mapping:
And the correct save order with this mapping: