我在实体框架中有一个名为雇佣的SQL Server表,其中有一个名为ID的键列。
如何使用实体框架从表中删除单个记录?
我在实体框架中有一个名为雇佣的SQL Server表,其中有一个名为ID的键列。
如何使用实体框架从表中删除单个记录?
当前回答
Employer employer = context.Employers.First(x => x.EmployerId == 1);
context.Customers.DeleteObject(employer);
context.SaveChanges();
其他回答
使用EntityFramework。Plus可以是一个选项:
dbContext.Employ.Where(e => e.Id == 1).Delete();
这里有更多的例子
您可以使用SingleOrDefault获取与您的条件匹配的单个对象,然后将其传递给EF表的Remove方法。
var itemToRemove = Context.Employ.SingleOrDefault(x => x.id == 1); //returns a single item.
if (itemToRemove != null) {
Context.Employ.Remove(itemToRemove);
Context.SaveChanges();
}
不需要先查询对象,可以通过它的id将它附加到上下文。 是这样的:
var employer = new Employ { Id = 1 };
ctx.Employ.Attach(employer);
ctx.Employ.Remove(employer);
ctx.SaveChanges();
或者,你可以将附加条目的状态设置为已删除:
var employer = new Employ { Id = 1 };
ctx.Entry(employer).State = EntityState.Deleted;
ctx.SaveChanges();
在实体框架6中,你可以使用Remove。 这也是一个很好的策略来确保你的连接是关闭的。
using (var context = new EmployDbContext())
{
Employ emp = context.Employ.Where(x => x.Id == id).Single<Employ>();
context.Employ.Remove(emp);
context.SaveChanges();
}
我使用实体框架与LINQ。下面的代码对我很有帮助;
1-用于多条记录
using (var dbContext = new Chat_ServerEntities())
{
var allRec= dbContext.myEntities;
dbContext.myEntities.RemoveRange(allRec);
dbContext.SaveChanges();
}
2-单张唱片
using (var dbContext = new Chat_ServerEntities())
{
var singleRec = dbContext.ChatUserConnections.FirstOrDefault( x => x.ID ==1);// object your want to delete
dbContext.ChatUserConnections.Remove(singleRec);
dbContext.SaveChanges();
}