从entity framework中删除单个logging?

(重述)

我有一个名为IDentity framework中的SQL Server表和一个名为ID键列。

如何使用entity framework从表中删除单个logging?

没有必要先查询对象,可以通过它的id将它附加到上下文中。 喜欢这个:

 var employer = new Employ { Id = 1 }; ctx.Employ.Attach(employer); ctx.Employ.Remove(employer); ctx.SaveChanges(); 

或者,您可以将附加条目的状态设置为删除*感谢Simon Belanger *:

 var employer = new Employ { Id = 1 }; ctx.Entry(employer).State = EntityState.Deleted; ctx.SaveChanges(); 

您可以使用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(); } 
 Employer employer = context.Employers.First(x => x.EmployerId == 1); context.Customers.DeleteObject(employer); context.SaveChanges(); 
  var stud = (from s1 in entities.Students where s1.ID== student.ID select s1).FirstOrDefault(); //Delete it from memory entities.DeleteObject(stud); //Save to database entities.SaveChanges(); 

我正在使用LINQ的entity framework。 以下代码对我有帮助;

1-对于多个logging

  using (var dbContext = new Chat_ServerEntities()) { var allRec= dbContext.myEntities; dbContext.myEntities.RemoveRange(allRec); dbContext.SaveChanges(); } 

2-对于单个logging

  using (var dbContext = new Chat_ServerEntities()) { var singleRec = dbContext.ChatUserConnections.FirstOrDefault(); // object your want to delete dbContext.ChatUserConnections.Remove(singleRec); dbContext.SaveChanges(); }