Reputation: 1
In a transaction, I should call many times SaveChanges() , or just call once ?
What is the difference between them? Thanks very much.
Can I only write once SaveChanges() before Commit() function ?
using (var transaction = entities.Database.BeginTransaction())
{
try
{
var product = entities.Product.Add(new Product()
{
Name = name,
Shape = shape
});
entities.SaveChanges(); // here
foreach (var image in images)
{
entities.Image.Add(new Image()
{
ProductId = product.Id,
Url = image
});
}
entities.SaveChanges(); // here
foreach (var specification in specifications)
{
entities.Specification.Add(new Specification()
{
Name = specification.Split(',')[0],
Value = specification.Split(',')[1].AsDecimal(),
ProductId = product.Id
});
}
entities.SaveChanges(); // here
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
return Json(new { status = false });
}
}
Upvotes: 0
Views: 472
Reputation: 30618
Most operations will not need a transaction. For example, your code can probably be rewritten without a transaction by adding the child entities to navigation properties on the parent, like this:
var product = entities.Product.Add(new Product()
{
Name = name,
Shape = shape
});
foreach (var image in images)
{
product.Images.Add(new Image()
{
Url = image
});
}
foreach (var specification in specifications)
{
product.Specifications.Add(new Specification()
{
Name = specification.Split(',')[0],
Value = specification.Split(',')[1].AsDecimal(),
});
}
entities.SaveChanges();
Your existing code does need a transaction and requires a SaveChanges after the product add, and at the end before committing the transaction. This is because you are referring to the product.Id of the added entity, which only gets generated when you call SaveChanges. You can safely remove the second SaveChanges in your code, as you are not referring to generated keys of the images.
Upvotes: 2
Reputation: 1182
You change as much as you need inside your set(s) and then call SaveChanges only once per context after you've made all your changes.
Upvotes: 0