LINQ and handling rollbacks
I have an image upload handler (.ASHX). I am storing image meta data in the database and am naming the image from the id of that entry into the database. I am using LINQ and getting the ID back after I call SubmitChanges. Then I use that id to save the image. I obviously want to rollback the insert if the File.SaveAs fails. Is my code below correct?
using (UserDataContext userDataContext = new UserDataContext())
{
GalleryImage galleryImage = new GalleryImage();
galleryImage.metaName = "some meta stuff";
userDataContext.GalleryImages.InsertOnSubmit(galleryImage);
System.Data.Common.DbTransaction transaction = userClassContext.Transaction;
userDataContext.SubmitChanges();
try
{
string targetPath = "somepath/" + galleryImage.Id;
file.SaveAs(target开发者_如何学JAVAFilePath);
}
catch
{
transaction.Rollback();
}
}
Thanks
It is partially correct.
You, however, need to explicitly create a transaction before calling SubmitChanges()
.
精彩评论