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

时光毁灭记忆、已成空白 提交于 2019-12-14 00:42:01

问题


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.


回答1:


//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




回答2:


You can't get ID before submitting data to SQL server because it is generated on server side. If you badly need to do so, I suggest generating ID on client side (which may be painful).

Another question is why do you need to access that ID before inserting a row, in most cases it may be misunderstanding of how linq2sql works.

Sometimes there is no Foreign Key set up in the database for the tables. To insert the ID in the referenced table, just take it from yourEntity.ID right after insert, it should be filled by the system. Don't forget to submit changes again.




回答3:


Well, in your code, user.ID includes the user id (if it was existed before, and of course if it's a new one). I'm not sure about that, but i think that SubmitChanges also automatically query the new ID of new records and fill the existing object identity property automatically, so in your case using user.ID won't cost additional query if you use it after the SubmitChanges (it'll be 0 if it's new record and you didn't call SubmitChanges)

But, if you want to use the id before calling SubmitChanges, the best way to define the 'ID' before adding it to the database is making the ID a uniqueidentifier on the database (System.Guid), and then simply inserting it with the GUID already defined in the INSERT statement.

Just notice that the insert could fail, and in that case you must make sure that if something went wrong anything you did while assuming user with the same ID as the Guid you're using exists will be rolled back.



来源:https://stackoverflow.com/questions/12728643/how-do-i-get-id-of-a-record-without-submitting-and-re-querying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!