Does Entity Framework saves related classes automatically?
- by herbatnic
Let's assume that we have such classes
public class A{
string someField { get; set; }
public virtual B B {get; set; }
}
public class B {
int someIntField {get; set; }
[ForeignKey("Id")]
[Required]
public virtual A A { get; set; }
}
In code I create new instances for both of them and making relation like:
A a = new A () { someField = "abcd"};
B b = new B () { someIntField = 42 };
A.B = b;
B.A = a;
Should I using DBContext to save both classes like that:
using (var db = new myDbContext()) {
myDbContext.As.Add(A);
myDbContext.Bs.Add(B);
myDBContext.SaveChanges();
}
Or saving it like that:
using (var db = new myDbContext()) {
myDbContext.As.Add(A);
myDbContext.SaveChanges();
}
is enough to store related objects into database?