LINQ to Entities - How best to obtain the IDENTITY value after calling SaveChanges()

后端 未结 1 843
后悔当初
后悔当初 2021-01-22 23:20

There have been numerous questions posed on this site relating to the retrieval of the IDENTITY after an insert is performed. The way we have been getting the identity is to mak

相关标签:
1条回答
  • 2021-01-23 00:17

    Yes, LINQ-to-Entities (and LINQ-to-SQL for that matter) will set the generated identity column back in the entity for you after SaveChanges is called. It will also do so for any foreign keys that couldn't be set ahead of time (for instance, a new parent row + a new child row are saved together, and after SaveChanges you'll have the right value in the child row's FK value).

    Your particular concern is documented in the 'Working with Entity Keys' page:

    http://msdn.microsoft.com/en-us/library/dd283139.aspx

    The particular section is 'Entity Keys and Added Objects' and the particular steps are:

    4 - If the INSERT operation succeeds, server-generated values are written back to the ObjectStateEntry.

    5 - The ObjectStateEntry updates the object with the server-generated value.

    0 讨论(0)
提交回复
热议问题