Does Entity Framework save related classes automatically?

c# ef-code-first entity-framework

Question

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?

1
11
10/23/2013 4:09:00 PM

Accepted Answer

From your example, if you instantiate new entity objects and then assign the child to the parent object's property, then EF will actually create a new child instance (record) and map it to the parent as a reference.

Your code snippet is a bit confusing because you've got reference from A to B and B to A but consider the following:

if you had 2 entities:

public class A
{
    public int Id;
}

public class B
{
    public int Id;
    public A A;
}

and when saving you did something like this:

A a = new A();
B  b = new B();
b.A = a;
dbcontext.SaveChanges();

then EF will create a new record for A, a new record for B and add the reference of newly created A record to B.

See this post for further details

7
5/23/2017 12:09:08 PM

Popular Answer

Saving the object that contains the other object is enough. It will automatically persist the changes to contained objects as well.

You could just create a small example and see for yourself what works.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow