从实体框架中删除单个记录? [英] Delete a single record from Entity Framework?
本文介绍了从实体框架中删除单个记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
(Reworded)
我在实体框架中有一个名为的SQL Server表,使用单键列
命名为 ID
。
I have a SQL Server table in Entity Framework named employ
with a single key column named ID
.
如何使用Entity Framework从表中删除单个记录?
How do I delete a single record from the table using Entity Framework?
推荐答案
首先不需要查询对象,可以通过其id将其附加到上下文中。
像这样:
It's not necessary to query the object first, you can attach it to the context by its id. Like this:
var employer = new Employ { Id = 1 };
ctx.Employ.Attach(employer);
ctx.Employ.Remove(employer);
ctx.SaveChanges();
或者,您可以将附件的状态设置为删除*感谢Simon Belanger *:
Alternatively, you can set the attached entry's state to deleted *Thanks to Simon Belanger *:
var employer = new Employ { Id = 1 };
ctx.Entry(employer).State = EntityState.Deleted;
ctx.SaveChanges();
这篇关于从实体框架中删除单个记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文