鉴于实体,
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<T>().Add(...)
和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 does not seem to handle cycles very well。
答案 0 :(得分:0)
您好需要调整映射:
modelBuilder.Entity<A>().HasOptional(a => a.DefaultB);
modelBuilder.Entity<A>().HasOptional(m => m.DefaultC);
modelBuilder.Entity<B>().HasRequired(m => m.A);
modelBuilder.Entity<C>().HasRequired(m => m.A);
使用此映射的正确保存顺序:
var a = new A() { Id = 3 };
context.As.Add(a);
context.SaveChanges();
var b = new B() { Id = 1};
var c = new C() { Id = 2 };
context.Bs.Add(b);
context.Cs.Add(c);
b.A = a;
c.A = a;
a.DefaultB = b;
a.DefaultC = c;
context.SaveChanges();