How do I delete one or more rows from my table using Linq to Entities *without* retrieving the rows first?

我与影子孤独终老i 提交于 2019-12-21 20:17:07

问题


I understand I can map a delete stored procedure to the delete method for a particular type.

However, this requires passing in a retrieved object to my context's DeleteObject method.

This is bad enough, but what if I want to delete 2000 rows? Can I do this with Linq to Entities without first retrieving those 2000 rows from the database and going through a loop calling DeleteObject?

If such functionality does not exist in Linq to Entities, and you know this to be the case, then please just say so and I'll investigate other options!

If it doesn't directly exist, could I achieve is by piping a Stored Proc through Linq to Entities?


回答1:


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.



来源:https://stackoverflow.com/questions/1601350/how-do-i-delete-one-or-more-rows-from-my-table-using-linq-to-entities-without

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!