如何在不先检索行的情况下使用Linq to Entities从我的表中删除一个或多个行? [英] How do I delete one or more rows from my table using Linq to Entities *without* retrieving the rows first?

查看:41
本文介绍了如何在不先检索行的情况下使用Linq to Entities从我的表中删除一个或多个行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以将删除存储过程映射到特定类型的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();

请参见 解决方案

Yes, you can do this. From this tip:

// 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();

See the full tip for details and complications.

这篇关于如何在不先检索行的情况下使用Linq to Entities从我的表中删除一个或多个行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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