我怎样才能插入实体编号实体框架? [英] How can I get Id of inserted entity in Entity framework?
本文介绍了我怎样才能插入实体编号实体框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有实体框架在Asp.net的问题。我想我的时候添加对象数据库来获取的ID值。我怎样才能做到这一点?
I have a problem with Entity Framework in Asp.net. I want to get the Id value whenever I add an object to database. How can I do this?
推荐答案
有pretty容易。如果您正在使用DB生成的ID(如在MS SQL IDENTITY
),你只需要实体添加到对象集
和的SaveChanges
对相关的ObjectContext
。 编号
会自动填写你:
It is pretty easy. If you are using DB generated Ids (like IDENTITY
in MS SQL) you just need to add entity to ObjectSet
and SaveChanges
on related ObjectContext
. Id
will be automatically filled for you:
using (var context = new MyContext())
{
context.MyEntities.AddObject(myNewObject);
context.SaveChanges();
int id = myNewObject.Id; // Yes it's here
}
默认情况下,实体框架遵循每个插入
与 SELECT SCOPE_IDENTITY()
时自动生成的编号
s的使用。
Entity framework by default follows each INSERT
with SELECT SCOPE_IDENTITY()
when auto-generated Id
s are used.
这篇关于我怎样才能插入实体编号实体框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文