Reputation: 3124
I have been working in Grails earlier and in Grails, same as Spring, service methods are transactional by default, we can change it through annotations if we want, but now I am working in ASP.net and I want to know if there is something similar to that. Or we must explicitly open transaction and close it at the end of each method. I am using entity framework...
Upvotes: 1
Views: 865
Reputation: 36453
This is pretty good article on transactions in EF Working with Transactions (EF6 Onwards)
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Transactions;
namespace TransactionsExamples
{
class TransactionsExample
{
static void StartOwnTransactionWithinContext()
{
using (var context = new BloggingContext())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
context.Database.ExecuteSqlCommand(
@"UPDATE Blogs SET Rating = 5" +
" WHERE Name LIKE '%Entity Framework%'"
);
var query = context.Posts.Where(p => p.Blog.Rating >= 5);
foreach (var post in query)
{
post.Title += "[Cool Blog]";
}
context.SaveChanges();
dbContextTransaction.Commit();
}
catch (Exception)
{
dbContextTransaction.Rollback();
}
}
}
}
}
}
Upvotes: 1
Reputation: 47375
With EntityFramework, all of your pending data storage operations will happen within a single unit of work (transaction) when you invoke SaveChanges
(or SaveChangesAsync
) on the DbContext
instance.
If you want to split up the work into multiple transactions, you would want to invoke SaveChanges
(or the async equivalent) each time you want to commit a transaction.
Upvotes: 1