如何使用Linq to Entities *从表中删除一行或多行而不先检索行?
-
05-07-2019 - |
题
我知道我可以将删除存储过程映射到特定类型的delete方法。
但是,这需要将检索到的对象传递给我的上下文的 DeleteObject
方法。
这已经够糟了,但如果我想删除2000行呢?我是否可以使用Linq to Entities执行此操作,而无需先从数据库中检索这些2000行并通过调用 DeleteObject
的循环?
如果 Linq to Entities中不存在此类功能,并且您知道情况就是如此,那么请您这样说,我会调查其他选项!
如果它不直接存在,我可以实现的是将存储过程通过Linq传递给实体吗?
解决方案
是的,你可以这样做。来自这个提示:
// Create an entity to represent the Entity you wish to delete
// Notice you don't need to know all the properties, in this
// case just the ID will do.
Category stub = new Category { ID = 4 };
// Now attach the category stub object to the "Categories" set.
// This puts the Entity into the context in the unchanged state,
// This is same state it would have had if you made the query
ctx.AttachTo("Categories", stub);
// Do the delete the category
ctx.DeleteObject(stub);
// Apply the delete to the database
ctx.SaveChanges();
参见完整提示了解详情和并发症。
不隶属于 StackOverflow