Answered by:
Delete data from multiple tables at a time

Question
-
Hi,
I want to insert, update or delete data from multiple tables in a single db call in entity framework
ex:
delete from emp where deptid=1
delete from dept where deptid=1
i want to do this transactions in a single call and also
i want to rollback if the second transaction fails means if both queries executed successfully then only commit otherwise it have to roll back first table deleted data also
thanks in advance
Thursday, May 21, 2015 3:56 PM
Answers
-
>i dont want to use sql queries in code.
Then just use SaveChanges(), it will introduce a transaction to ensure that all the pending changes are either completed successfully or rolled back. It will result in multiple SQL queries, though.
David
- Marked as answer by Fred Bao Monday, June 1, 2015 9:24 AM
Tuesday, May 26, 2015 1:52 PM
All replies
-
Simply
using (var db = new YourDbContext()) { var sql = @" delete from emp where deptid=1; delete from dept where deptid=1; "; db.Database.ExecuteSqlCommand(TransactionalBehavior.EnsureTransaction,sql); }
David
David http://blogs.msdn.com/b/dbrowne/
- Edited by davidbaxterbrowneMicrosoft employee Thursday, May 21, 2015 5:01 PM
Thursday, May 21, 2015 5:01 PM -
Using (db conext)_
{
Using (scope = new system.transaction)
{
delete
delete
scope.complete()
}
{
If code doesn't reach scope.complete() and it blewup, then the Using statement for the Transaction.Scope is going to rollback all transactions within rhe scope.
Thursday, May 21, 2015 5:42 PM -
Hi David,
thank you for replying.
i dont want to use sql queries in code.
- Edited by Kumar Jalli Tuesday, May 26, 2015 8:11 AM
Tuesday, May 26, 2015 8:10 AM -
>i dont want to use sql queries in code.
Then just use SaveChanges(), it will introduce a transaction to ensure that all the pending changes are either completed successfully or rolled back. It will result in multiple SQL queries, though.
David
- Marked as answer by Fred Bao Monday, June 1, 2015 9:24 AM
Tuesday, May 26, 2015 1:52 PM