Handling auto-incrementing IDENTITY SQL Server fields with LINQ to SQL in C#

Posted by Maxim Z. on Stack Overflow See other posts from Stack Overflow or by Maxim Z.
Published on 2010-06-17T04:02:42Z Indexed on 2010/06/17 4:03 UTC
Read the original article Hit count: 252

I'm building an ASP.NET MVC site that uses LINQ to SQL to connect to SQL Server, where I have a table that has an IDENTITY bigint primary key column that represents an ID.

In one of my code methods, I need to create an object of that table to get its ID, which I will place into another object based on another table (FK-to-PK relationship).

At what point is the IDENTITY column value generated and how can I obtain it from my code?

Is the right approach to:

  1. Create the object that has the IDENTITY column
  2. Do an InsertOnSubmit() and SubmitChanges() to submit the object to the database table
  3. Get the value of the ID property of the object

© Stack Overflow or respective owner

Related posts about c#

Related posts about sql-server