I use CodeFirst EntityFramework
I have a class
public class MenuItem { public int Id { get; set; } public string Title { get; set; } public int SortNumber { get;set; } } I need that when it is created in SortNumber Id .
How i do it now
MenuItem menuItem = new MenuItem(); menuItem.Title = "Hallow"; db.MenuItems.Add(menuItem); db.SaveChanges(); menuItem.SortNumer = menuItem.Id; db.SaveChanges(); This code works, but it is no longer atomic, and if the server fails, there is a risk that the element will be created, but SortNumber will not be assigned correctly.
How do I solve this at the moment, create a transaction on top of these operations, to achieve the integrity of the database and the atomicity of the operation.
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.RepeatableRead })) { MenuItem menuItem = new MenuItem(); menuItem.Title = "Hallow"; db.MenuItems.Add(menuItem); db.SaveChanges(); menuItem.SortNumer = menuItem.Id; db.SaveChanges(); scope.Complete(); } Are there any other alternatives, maybe somehow easier to do? How to do it right?
In this case, you just SortNumber to make SortNumber equal to Id , but this is an example, sometimes you need to form some line based on Id and write it to the same class, so that the answer would be suitable for these options.
The code above is written for EntityFramework 6 without Core but I am interested in the solution for the Core version.