使用 ADO.NET 实体获取标识行值
我在 SQL Server 2008 数据库中有下表:
User
--------------------------------------------------------
Id Numeric(18, 0) | Identity(1, 1) PK not null
Name Nchar(20) | Not null
我正在使用 ADO.NET 实体数据模型来执行以下操作:
MyEntities entities;
try
{
entities = new MyEntities();
if (entities.User.Count(u => u.Name == userName) == 0)
{
entities.User.AddObject(new User()
{
Name = userName
});
resultCode = 1;
entities.SaveChanges();
}
else
{
resultCode = 2;
}
}
catch
{
resultCode = 3;
}
finally
{
if (entities != null)
entities.Dispose();
}
如何获取添加的新用户的 User.Id?
I have the following table in SQL Server 2008 database:
User
--------------------------------------------------------
Id Numeric(18, 0) | Identity(1, 1) PK not null
Name Nchar(20) | Not null
I'm using an ADO.NET Entity Data model to do:
MyEntities entities;
try
{
entities = new MyEntities();
if (entities.User.Count(u => u.Name == userName) == 0)
{
entities.User.AddObject(new User()
{
Name = userName
});
resultCode = 1;
entities.SaveChanges();
}
else
{
resultCode = 2;
}
}
catch
{
resultCode = 3;
}
finally
{
if (entities != null)
entities.Dispose();
}
How can I get User.Id for new User added?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的模型配置正确并且您的 Id 属性标有
StoreGeneratePattern.Identity
,您只需调用以下命令:If your model is configured correctly and you have Id property marked with
StoreGeneratedPattern.Identity
you need simply call this:尝试保留对用户对象的引用。一旦调用 SaveChanges(),Id 就会自动更新。这是对您的代码的修改以进行演示:
Try keeping a reference to the user object. Once SaveChanges() is called, the Id should automatically be updated. Here's a modification of your code to demonstrate: