none
How to retrieve the last inserted IDENTITY in Linq to SQL RRS feed

Answers

  • You don't need to, Linq to SQL automatically sets the indentity value of your class with the ID generated when you insert a new record. Just access the property.

     

    Tuesday, August 26, 2008 1:39 PM
    Answerer

All replies

  • You don't need to, Linq to SQL automatically sets the indentity value of your class with the ID generated when you insert a new record. Just access the property.

     

    Tuesday, August 26, 2008 1:39 PM
    Answerer
  • Sorry, my native language is spanish, I´ll try to clarify my answer.

     

    I just need to take the Identity, immediately, after I insert the record, that's the code sample:

     

    Dim aUser As New User

     

    aUser.Name = Me.Name

    aUser.Lastname = Me.Lastname

     

    uDatabase.Users.InsertOnSubmit(aUser)

    uDatabase.SubmitChanges()

     

    Return aUser.ID    'But in this moment the User ID = 0, and I need the real Identity inserted.

     

    Tuesday, August 26, 2008 1:50 PM
  • Not sure what's going wrong at your end, the ID field should be updated by the Datacontext. This example I ran against a Northwind DataContext and it worked okay:

     

    Code Snippet

    Dim dm As New DB.NorthwindDataContext

    'create new order

    Dim tmp As New DB.Employee()

    tmp.LastName = "Smith"

    tmp.FirstName = "John"

    dm.Employees.InsertOnSubmit(tmp)

    dm.SubmitChanges()

    'saved

    Console.WriteLine("New item has ID {0}", tmp.EmployeeID)

    Console.WriteLine("Press any key to continue")

    Console.ReadKey()

     

     

    1) Check your table has a primary key defined. If it does not LINQ to SQL won't be able to retrieve and update the data.

    2) check the SQL being generated (use datacontext.log = Console.Out to see )

    Tuesday, August 26, 2008 2:05 PM
    Answerer
  • Of course it's works fine, I don't know when then ID was empty. I think (as you said) in that moment the table haven't a primary key defined, and I don't try again later. Thank you.

    Tuesday, August 26, 2008 3:22 PM