.NET MVC 3 Rollback in Dbcontext

in MVC 3 can you drop the database after calling DbContext.SaveChanges ()?

My feature 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 an ImageFile entry into db, and then using auto-incremented id as the image file name, save the image file in another place. When System.IO fails, I would like to roll back 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. 
+4
source share
2 answers

You must wrap your DbContext in a database transaction, either using TransactionScope or creating a DbContext using a DbConnection that runs inside the transaction:

 using (var con = new SqlConnection(conStr)) { con.Open(); using (var tran = con.BeginTransaction()) { var img = new Image(); using (var db = new BipEntities(con)) { db.Images.AddObject(img); db.SaveChanges(); } // Write to disk here. WriteStuffToDisk(stuff, img.Id); tran.Commit(); } } 
+2
source

Basically, .saveChanges() is your fixator. If you want a rollback, just do not .saveChanges and just close your database access level, no changes will be saved.

 using(var db = new dbconnection()) { myEntity item = new myEntity { Name = "Hello" }; db.tblofmyEntities.AddObject(item); if (item.Name != "FOO") db.SaveChanges(); } 

The item will be saved because its name is not "FOO". if it is "FOO", it will not be saved. When the application reaches } , so the item will not be saved. You can call the .AddObject() function before or inside the if-block, it does not really matter.

0
source

Source: https://habr.com/ru/post/1388288/


All Articles