Created
December 6, 2012 06:49
-
-
Save mikehibm/4222287 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() { | |
//EFと同じ接続文字列を使って先にSqlConnectionを作成。 | |
using (var sqlConnection = new SqlConnection(new MyEntities().Database.Connection.ConnectionString)) { | |
//作成済みのSqlConnectionを使ってDbContextを作成。 | |
using (var context = new MyEntities(sqlConnection)) { | |
//EntityConnectionのOpenメソッドを呼ぶ。 | |
IDbConnection entityConnection = ((IObjectContextAdapter)context).ObjectContext.Connection; | |
entityConnection.Open(); | |
//EntityConnectionに対してトランザクションを開始。 | |
using (var tr = entityConnection.BeginTransaction()) { | |
try { | |
//Reflectionを使ってEntityTransactionからSqlTransactionを取得する。 | |
var sqlTran = (SqlTransaction)tr.GetType().InvokeMember("StoreTransaction", | |
BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.InvokeMethod | |
| BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.NonPublic, null, tr, new object[0]); | |
//1. ADO.NETで独自のSQL文を実行。 | |
var sql = "UPDATE [Products] SET [Price] = [Price] * 1.1 "; | |
var cmd = sqlConnection.CreateCommand(); | |
cmd.Transaction = sqlTran; | |
cmd.CommandText = sql; | |
cmd.ExecuteNonQuery(); | |
//2. DbContextでProductsを更新。 | |
var product = context.Products | |
.FirstOrDefault(); | |
product.Price /= 1.1M; | |
context.SaveChanges(); | |
tr.Commit(); | |
} | |
catch (Exception) { | |
tr.Rollback(); | |
throw; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment