in MVC 3 is it possible to rollback the database after calling DbContext.SaveChanges() ?
My entities class:
public class BipEntities : DbContext
{
public DbSet<Page> Pages { get; set; }
public DbSet<ImageFile> ImageFiles { get; set; }
}
What I’m trying to do is insert a ImageFile record into the db, then by using the auto-incremented id as the image filename, save the image file into somewhere else.
When System.IO fails, I would like to rollback the database.
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();
However, the above code gives me this error message:
EntityConnection can only be constructed with a closed DbConnection.
You should wrap your
DbContextin a database transaction, either using aTransactionScopeor creating theDbContextusing aDbConnectionthat runs inside a transaction: