Does Entity Framework saves related classes automatically?

Posted by herbatnic on Stack Overflow See other posts from Stack Overflow or by herbatnic
Published on 2013-10-23T15:50:38Z Indexed on 2013/10/23 15:53 UTC
Read the original article Hit count: 136

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about entity-framework