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.

  • that is, do you need a calculated field based on Id? - tym32167
  • @ tym32167 it is calculated only when it is created, then other values ​​will need to be written there, that is, there should not be a hard binding - Dmitry Polyanin
  • That is, you need something like a trigger on the insert in the database, only as a construct in EF? - tym32167
  • @ tym32167 is one of the ways to set an object, there are other ways, that is, the trigger that works always does not fit - Dmitry Polyanin
  • @ tym32167 example: for the test database I fill in the forum messages in the initializer and insert Id into the message text for easy debugging. But this will not happen in production, and there the message is specified from the POST request. - Dmitry Polyanin

0