加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – DbSet.Add&DbSet.Remove使用EntityState.Added和Entit

发布时间:2020-12-15 22:17:20 所属栏目:百科 来源:网络整理
导读:在实体框架6中有多种添加/删除实体的方式,例如对于添加实体,我们可以使用: – b.Students.Add(student);db.SaveChanges(); 要么 db.Entry(student).State = EntityState.Added;db.SaveChanges(); 和删除对象时类似: – db.Entry(studentToDelete).State =
在实体框架6中有多种添加/删除实体的方式,例如对于添加实体,我们可以使用: –

b.Students.Add(student);
db.SaveChanges();

要么

db.Entry(student).State = EntityState.Added;
db.SaveChanges();

和删除对象时类似: –

db.Entry(studentToDelete).State = EntityState.Deleted;
db.SaveChanges();

要么

db.Remove(StudentToDelete)
db.SaveChanges();

我没有找到太多关于差异的资源,大多数在线教程都提到了两种方法,就好像它们是相同的.但是我已经阅读了文章link的回复是使用dbset.Add设置实体的状态及其所有相关的实体/集合添加,而使用EntityState.Added也会将所有相关的实体/集合添加到上下文但是将它们保留为未修改,同样适用于dbset.Remove& EntityState.Deleted

这些差异也正确吗?

编辑

据我所知,图形操作意味着父母和孩子都被删除/添加,如果父母被标记为删除或添加.所以我做了这两个测试: –

using (var db = new TestContext())
{
    var a = new Department { DepartmentName = "Shipping" };
    var b = new Employee { FirstName = "Bob",LastName = "Dodds",Department = a };
    db.Entry(b).State = EntityState.Added;
    db.SaveChanges();
}



using (var db = new TestContext())
{
    var a2 = new Department { DepartmentName = "Production" };
    var b2 = new Employee { FirstName = "Sarah",LastName = "Gomez",Department = a2 };
    db.Employees.Add(b2);
    db.SaveChanges();
}

两者都增加了部门和员工.那你能不能这样做吗?

解决方法

来自Lerman&米勒的DbContext书(第80页):

Calling DbSet.Add and setting the State to Added both achieve exactly the same thing.

这是:

If the entity is not tracked by the context,it will start being tracked by the context in
the Added state. Both DbSet.Add and setting the State to Added are graph operations—
meaning that any other entities that are not being tracked by the context and are reachable
from the root entity will also be marked as Added. If the entity (the root entity – my addiditon) is already tracked
by the context,it will be moved to the Added state.

请注意,在您引用的问题中未正确回答这个问题.这本书是用EF 4.3编写的,并没有提到自引入DbContext后EF 4.1以来的任何重大变化.

将实体的状态设置为已删除(通过DbSet.Remove()或通过将Entry(实体).State设置为Deleted)不是图形操作.它只影响实体的状态,而不影响其对象图中的实体.

后者适用于除Add之外的任何实体状态.

此规则的一个例外是在数据库和EF模型中配置了级联删除.在与隐藏联结表的多对多关联中,级联删除是默认的,因此当根实体标记为删除时(通过将其状态设置为已删除或从其DbSet中删除),始终会删除联结记录. .

例如,让A和B具有多对多关联.联结表AB仅在数据库中,而不在类模型中.如果从数据库中获取A(没有包含它的B)并删除它,则删除A及其AB记录,但不删除任何B.

当在一对多关联中配置级联删除时,删除“1”实体时将删除“多个”实体.如果A和B具有一对多关联,则删除A也将删除其B.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读