实体框架 Remove vs EntityState.Deleted [英] entity framework Remove vs EntityState.Deleted

查看:9
本文介绍了实体框架 Remove vs EntityState.Deleted的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种说法有什么区别?

What is the diff between these two statements?

两者都应该删除一个实体.

Both should delete an entity.

 _context.Entry(new Schoolyear { Id = schoolyearId }).State = EntityState.Deleted;
 _context.Schoolyears.Remove(new Schoolyear { Id = schoolyearId });

对于那些不知道 EF 扩展的人:

and for those who does not know the EF Extensions:

 _context.Schoolyears.Delete(s => s.Id == schoolyearId);

那就更酷了:D

推荐答案

它们是一样的,但都会失败.EF 在内部使用 ObjectManager 来跟踪 EF 使用的所有元素.通过使用 EF 的检索功能或通过使用 _context.Schoolyears.Add(obj) 向 EF 添加新条目来添加到 ObjectManager 的条目.

They are the same but both will fail. EF internally uses an ObjectManager to keep track of all elements used by EF. Entries to the ObjectManager are added by using retrieval functions of EF or by adding new entries to the EF with using _context.Schoolyears.Add(obj).

未存储在对象管理器中的引用条目通常会创建 InvalidOperationException 异常.以下行为类似:

Referencing entries not stored in the object manager will usually create InvalidOperationException exceptions. The behavior of the following is similar:

Schoolyear year = context.Schoolyears.Single(x => x.Name == "2013");
_context.Schoolyears.Remove(year);
_context.SaveChanges();

Schoolyear year = context.Schoolyears.Single(x => x.Name == "2013");
_context.Entry(year).State = EntityState.Deleted;
_context.SaveChanges();

但 EF 在第一种方法中会进行更多检查和状态更改活动.

but EF does some more checks and status change activities in the first approach.

如果可能,我总是更喜欢第一方法.

I would always prefer the first approach if possible.

在游戏的另一端有 EntityFramework.Extended.该库允许对 EF 上下文进行大规模更新/删除.

On the other side of the game there's EntityFramework.Extended. This library allows mass updates/deletes on EF contexts.

这个库不使用ObjectManager,所以你可以使用

This library does not use the ObjectManager, therefore you are allowed to use

 _context.Schoolyears.Delete(s => s.Id == schoolyearId);

提示:你也可以使用(首选)

Hint: You can also use (preferred)

 _context.Schoolyears.Where(s => s.Id == schoolyearId).Delete();

警告:请确保不要在 EF 和 EF.Extended 中同时操作对象.这可能会导致不可预知的结果或异常.

Warning: Please ensure that you do not manipulate objects at the same time in EF and EF.Extended. This Could cause unpredictable results or exceptions.

这篇关于实体框架 Remove vs EntityState.Deleted的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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