Created
December 6, 2012 06:14
-
-
Save mikehibm/4222166 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(); | |
//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