I have the following statements:
int newId = db.OnlinePayments.Max(op => op.InvoiceNumber) + 1;
opi.InvoiceNumber = newId;
await db.SaveChangesAsync();
The column InvoiceNumbermust be unique, but this approach is dangerous, since from the moment you get the value for newId, you can add another record to the table. I read that table locking will fix this, but I'm not sure how I should achieve this using the Entity Framework.
In addition, I thought that perhaps doing this in a transaction would be enough, but someone said that it is not.
Update
Suppose this is a table definition in the Entity Framework.
public class OnlinePaymentInfo
{
public OnlinePaymentInfo()
{
Orders = new List<Order>();
}
[Key]
public int Id { get; set; }
public int InvoiceNumber { get; set; }
public int Test { get; set; }
}
Now, obviously, Idis the primary key of the table. And I can note InvoiceNumberhow Idenity is with this:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int InvoiceNumber { get; set; }
Now this will work if I do something like this:
var op = new OnlinePayment { Test = 1234 };
db.OnlinePayments.Add(op);
await db.SaveChangesAsync();
InvoiceNumber. , , . :
var op = await db.OnlinePayments.FindAsync(2);
op.Test = 234243;
//Do something to invalidate/change InvoideNumber here
db.SaveChangesAsync();
0, , , , Identity. , .