MVC 3では、DbContext.SaveChanges()を呼び出した後にデータベースをロールバックすることは可能ですか?
私のエンティティクラス:
public class BipEntities : DbContext
{
public DbSet<Page> Pages { get; set; }
public DbSet<ImageFile> ImageFiles { get; set; }
}
私がやろうとしているのは、ImageFileレコードをデータベースに挿入し、自動インクリメントされたIDを画像ファイル名として使用して、画像ファイルを別の場所に保存することです。System.IOに障害が発生した場合、データベースをロールバックしたいと思います。
BipEntities db = new BipEntities();
db.Database.Connection.Open();
DbTransaction tranx = db.Database.Connection.BeginTransaction();
ImageFile img = new ImageFile { CreatedAt = DateTime.Now };
db.ImageFiles.Add(img);
db.SaveChanges();
string filename = "img" + img.Id.ToString() + ".png";
try {
//Works on system IO to process file
tranx.Commit();
} Catch ( Exception) {
tranx.Rollback();
}
db.Database.Connection.Close();
ただし、上記のコードでは、次のエラーメッセージが表示されます。
EntityConnection can only be constructed with a closed DbConnection.