调用SaveChanges()后,如果实体映射到存储过程,如何获取一个实体的身份 [英] How to obtain the identity of an entity after calling SaveChanges() when the entity is mapped to stored procedures
问题描述
当使用映射到表的实体时,我可以添加一个新实体,调用 dataContext.SaveChanges();
然后我自动实例化的新实体的ID属性填充数据库中的标识列中的值。
当实体映射到存储过程时,如何实现? INSERT存储过程必须做一些特殊的事情,或者我必须在 dataContext.SaveChanges();
?
示例
传统方式
var newCustomer = new Customer
{
Name =Fred,
年龄= 24
};
// newCustomer.Id为null
dataContext.Customers.Add(newCustomer);
dataContext.SaveChanges()
// newCustomer.Id是什么数据库标识列设置为。
映射到存储过程。
var newCustomer = new Customer
{
Name =Fred,
Age = 24
};
// newCustomer.Id为null
dataContext.Customers.Add(newCustomer);
dataContext.SaveChanges()
// newCustomer.Id为null
如果您在数据库中使用Identity列,请确保您的存储过程包含:
SELECT Scope_Identity()AS Id
调用 INSERT
还要确保您的实体模式中的PK正确配置为 StoreGeneratedPattern
设置为 Identity
(如果您使用从数据库更新,则应自动使用)
We are using Entity Framework 4.0 and we have an entity that is mapped to stored procedures provided by our DBA. The Insert, Update, and Delete functions in the mapping details all have their own stored procedures.
When using entities that are mapped to tables I am able to add a new entity, call dataContext.SaveChanges();
and then the new entity I instantiated automatically has its ID property populated with the value from the identity column in the database.
How can this be accomplished when the entity is mapped to stored procedures? Does the INSERT stored procedure have to do something special and/or do I have to do something special on dataContext.SaveChanges();
?
Example
Traditional way
var newCustomer = new Customer
{
Name = "Fred",
Age = 24
};
// newCustomer.Id is null
dataContext.Customers.Add(newCustomer);
dataContext.SaveChanges()
// newCustomer.Id is what database identity column was set to.
Mapped to stored procedures.
var newCustomer = new Customer
{
Name = "Fred",
Age = 24
};
// newCustomer.Id is null
dataContext.Customers.Add(newCustomer);
dataContext.SaveChanges()
// newCustomer.Id is null
If you are using Identity column in database make sure that your stored procedure contains:
SELECT Scope_Identity() AS Id
after calling INSERT
Also make sure that PK in your entity mode is correctly configured with StoreGeneratedPattern
set to Identity
(should be automatically if you used Update from database)
这篇关于调用SaveChanges()后,如果实体映射到存储过程,如何获取一个实体的身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!