Created
December 6, 2012 05:57
-
-
Save mikehibm/4222098 to your computer and use it in GitHub Desktop.
EFTransactionサンプルコード
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
private void UpdateProducts() { | |
using (var context = new MyEntities()) { | |
using (var cn = context.Database.Connection) { | |
cn.Open(); | |
using (var tr = context.Database.Connection.BeginTransaction()) { | |
try { | |
//1. ADO.NETで独自のSQL文を実行。 | |
var sql = "UPDATE [Products] SET [Price] = [Price] * 1.1 "; | |
var cmd = cn.CreateCommand(); | |
cmd.Transaction = tr; | |
cmd.CommandText = sql; | |
cmd.ExecuteNonQuery(); | |
tr.Commit(); | |
} | |
catch (Exception) { | |
tr.Rollback(); | |
throw; | |
} | |
} | |
} | |
} | |
using (var context = new MyEntities()) { | |
//2. DbContextでProductsを更新。 | |
var product = context.Products | |
.FirstOrDefault(); | |
product.Price /= 1.1M; | |
context.SaveChanges(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
上の例では別のContextを使っているのでこれはエラーにはならない。
ただしこれだと1つめの更新処理と2つめの更新処理を同一のトランザクション内で実行出来ない。