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?


source to share

2 answers

If you set the properties of this string "ID" to "Auto-Generated Value" = true and "Auto-Sync" to "OnInsert"

alt text

..... 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);


    int newDinnerID = upcoming.DinnerID;


The "newDinnerID" should now contain the newly added IDENTITY.




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)]




All Articles