My entity classes are like this:
public class A{
[Key]
string Name;
B DefaultB;
ICollection<B> Bs;
}
public class B{
[Key]
int Key;
}
public class C{
[Key]
string Key;
A MyA;
B MyB;
public C(A a,B b){
MyA=a;
MyB=b;
}
}
public class MyDbContext:DbContext{
public DbSet<A> As
public DbSet<B> Bs
public DbSet<C> Cs
}
The testing code is like this:
main(){
A a=new A();
B b=new B();
a.addB(B);
MyDbContext m=new MyDbContext();
m.As.Add(a);
m.SaveChanges();
C c=new C(a,b);
m.Cs.Add(c);
m.SaveChanges();
}
The problem is when I add the c to the context, it tries to add a and b again in the context, which causes an exception because they are already in it. This should not happen.
How can I solve this?
Thanks
If you do this all in a single context you only need one single
SaveChangesat the end:EF will only create a single
Aand a singleBand use both in the relationships inband inc.If you need – for some reason – to create two contexts you must reattach the entites you inserted in the first context to avoid a second INSERT and duplication in the database: