I have the following statements:
int newId = db.OnlinePayments.Max(op => op.InvoiceNumber) + 1;
opi.InvoiceNumber = newId;
await db.SaveChangesAsync();
The InvoiceNumber
column should be unique but this approach is dangerous because from the time I get the value for newId
, another record could be added to the table. I read that locking the table would fix this but I'm not sure how I should achieve this with Entity Framework.
Also, I thought maybe doing this in a Transaction would be enough but someone said that it's not.
Update
Suppose this is the table definition in 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; }
//..rest of the table
}
Now, obviously Id
is the primary key of the table. And I can mark InvoiceNumber
as Idenity 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();
And it will automatically generate a unique number for InvoiceNumber
. But I need this number to change whenever I change the record. For instance:
var op = await db.OnlinePayments.FindAsync(2);
op.Test = 234243;
//Do something to invalidate/change InvoideNumber here
db.SaveChangesAsync();
I tried to set it to 0
but when I try to assign a value to it, I get an error indicating that I cannot assign to an Identity column. That's the reason I tried to do this manually.