Skip to content

Instantly share code, notes, and snippets.

@mikehibm
Created December 6, 2012 06:14
Show Gist options
  • Save mikehibm/4222166 to your computer and use it in GitHub Desktop.
Save mikehibm/4222166 to your computer and use it in GitHub Desktop.
EFTransactionサンプルコード
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