I have 2 Linq2Sql classes: Parent
and Child
. I want to do things like removing all children for a parent, or updating all child records. In SQL I would have written:
delete Child where ParentID = @p
or
update Child set Val = Val+1 where ParentID = @p
I can do this in Linq the brute force way inside the Parent
class:
Children.ToList().ForEach(c => c.DeleteOnSubmit()); // DeleteOnSubmit is my own method
and
Children.ToList().ForEach(c => c.Val++);
But given Linq's inherent performance penalty on ForEach loops, this seems like a very inefficient way to do things. Is there some way of achieving the desired end that will fire off exactly one query?
You can drag the SPROC to your DBML file and it will generate a rich method in your databasecontext class. Show activity on this post. First, you can find a list of the items you want to delete.
You can delete rows in a database by removing the corresponding LINQ to SQL objects from their table-related collection. LINQ to SQL translates your changes to the appropriate SQL DELETE commands. LINQ to SQL does not support or recognize cascade-delete operations.
You can update rows in a database by modifying member values of the objects associated with the LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL UPDATE commands.
Extensions Update method. The Update method is able to bulk update for a set of records with same set of update values. Records. Update(new => Record { Quantity = 100 });
For these cases you can use the DataContext.ExecuteCommand method to directly execute SQL on your database. For example:
dataContext.ExecuteCommand("delete Child where ParentID = {0}", parentId);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With