How do I delete one or more rows from my table using Linq to Entities *without* retrieving the rows first?
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 Entitie开发者_StackOverflow中文版s, 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?
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.
精彩评论