我如何获得了创纪录的ID,而无需提交并重新查询? [英] How do I get Id of a record without submitting and re-querying?

查看:181
本文介绍了我如何获得了创纪录的ID,而无需提交并重新查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有被设置为自动递增的ID(INT明显)。

 变种DC =新的DataContext([STRING ]); 

VAR usersTable = dc.GetTable<&的audit_user GT;();

VAR用户= usersTable.FirstOrDefault(O => o.Username.Equals(NAME));

如果(用户== NULL)
{
用户=新的audit_user()
{
=用户名NAME
};

usersTable.InsertOnSubmit(用户);
}

//这里 - 我需要访问的用户ID

dc.SubmitChanges();

有关更多的上下文,请参阅标签。


解决方案

//这里 - 我需要访问的用户ID




其实你的不要。如果你一直使用LINQ-2-SQL,您可以指定用户的实体而不是设置user.id(为什么你需要的ID最可能的原因)来填充的关系。



因此,而不是做

  somerelated_table.fk_user_id = user.id 

  somerelated_table.user =用户

的LINQ-2-SQL将处理的正确分配在user.id当你调用的SubmitChanges。另外作为奖励它都将在一个事务中完成的。这就是LINQ-2-SQL的美感。



如果您需要的ID为一些操作的没有使用LINQ-2-SQL中,无论如何能做到这一点的SubmitChanges后也没什么关系反正


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.

解决方案

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

这篇关于我如何获得了创纪录的ID,而无需提交并重新查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆