Created
November 2, 2012 20:28
-
-
Save JulianR/4004127 to your computer and use it in GitHub Desktop.
EF transactions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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