Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

c# - Does Entity Framework save related classes automatically?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...