Search code examples
c#sqllinq-to-sqlauto-incrementinsertonsubmit

How do I get Id of a record without submitting and re-querying?


I have an ID that is set to auto increment (int obviously).

var dc = new DataContext([STRING]);

var usersTable = dc.GetTable<Audit_User>();

var user = usersTable.FirstOrDefault(o => o.Username.Equals("NAME"));

if (user == null)
{
   user = new Audit_User()
   {
      Username = "NAME"
   };

   usersTable.InsertOnSubmit(user);
}

//HERE - I need access to the user Id

dc.SubmitChanges();

For more context, please see the tags.


Solution

  • //HERE - I need access to the user Id

    Actually you do not. If you consistently use linq-2-sql you can assign the user entity instead of setting the user.id to populate a relation (most probable cause why you need the ID).

    So instead of doing

    somerelated_table.fk_user_id = user.id
    

    you do

    somerelated_table.user = user
    

    Linq-2-sql will handle the proper assignment of the user.id when you call SubmitChanges. Plus as a bonus it will all be done in a single transaction. That is the beauty of linq-2-sql.

    If you need the Id for some manipulation without using linq-2-sql, you can anyhow do it after the submitchanges and it will not matter anyway