Skip to content

Instantly share code, notes, and snippets.

@njmube
Forked from mikehibm/UpdateProducts2.cs
Last active August 29, 2015 14:23
Show Gist options
  • Save njmube/f8b68a9ca71d8c19c7bc to your computer and use it in GitHub Desktop.
Save njmube/f8b68a9ca71d8c19c7bc to your computer and use it in GitHub Desktop.
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