How to get identity id when insert row into db using linq
2 answers
If you set the properties of this string "ID" to "Auto-Generated Value" = true and "Auto-Sync" to "OnInsert"
..... just read it after you save your changes using .SubmitChanges()
. No special tricks or anything else necessary
So in the case of the NerdDinner example:
using(NerdDinnerContext ctx = new NerdDinnerContext())
{
Dinner upcoming = new Dinner();
// set all properties for the dinner
upcoming.EventDate = DateTime.Today.AddDays(30);
ctx.Dinners.InsertOnSubmit(upcoming);
ctx.SubmitChanges();
int newDinnerID = upcoming.DinnerID;
}
The "newDinnerID" should now contain the newly added IDENTITY.
Mark
+4
source to share