Entity Framework是否自动保存相关类? [英] Does Entity Framework save related classes automatically?

查看:75
本文介绍了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

这篇关于Entity Framework是否自动保存相关类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆