How to get identity id when insert row into db using linq
How to get the identity when inserting a row into a db using linq?
+2
mrblah
source
to share
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
marc_s
source
to share
LINQ to SQL should automatically retrieve the ID of the inserted object and update the field you mapped to the primary key accordingly, provided the displayed PK property is marked as [Column(IsDbGenerated=true)]
.
+1
Pavel Minaev
source
to share