是否实体框架自动保存相关的类?

是否实体框架自动保存相关的类?

问题描述:

假设我们有这样的类

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;



我应该使用的DbContext保存两个类这样的:

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();
}

或保存这样的:

using (var db = new myDbContext()) {
    myDbContext.As.Add(A);
    myDbContext.SaveChanges();
}



足以相关的对象存储到数据库中?

is enough to store related objects into database?

从你的例子,如果你实例化新的实体对象,然后分配孩子的父对象的属性,则EF实际上会创建一个新的子实例(记录),并将其映射到父作为参考。

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.

您的代码片段是有点混乱,因为你已经从一个有参考到b和b到A,但考虑以下几点:

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

如果你有2个实体:

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();



然后EF将创建一个新的记录,对B的新纪录,并添加新的参考创建一个记录到b。

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