Entity Framework是否自动保存相关类?
我们假设我们有这样的类
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;
我应该使用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.
您的代码片段有点混乱,因为您有从A到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将为A创建一个新记录,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