Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
EF transactions
using System.Data.Entity;
using System.Data;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
using (var ctx = new DataContext())
{
var test = new Test()
{
Bar = 1,
Foo = "bla"
};
ctx.Tests.Add(test);
ctx.SaveChanges();
}
}
}
public class Test
{
public int ID { get; set; }
public string Foo { get; set; }
public int Bar { get; set; }
}
public class DataContext : DbContext
{
public IDbSet<Test> Tests { get; set; }
public override int SaveChanges()
{
if (this.Database.Connection.State != ConnectionState.Open)
{
this.Database.Connection.Open();
}
using (var tran = this.Database.Connection.BeginTransaction())
{
this.Database.ExecuteSqlCommand("insert into Tests (Foo, Bar) values ('test', 2)");
var result = base.SaveChanges();
tran.Commit();
return result;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment