EF通用存储库从新插入的通用实体获取Id [英] EF Generic Repository get Id from new inserted generic entity
问题描述
我的所有实体都有属性ID。数据库中的所有表都具有自动生成的整数身份ID作为主键。
All my entities has property Id. All my tables in database has auto-generated integer identity Id as primary key.
我有通用的方法来创建实体。
I have generic method to Create entities.
在实体插入数据库后有没有办法获取实体ID?
Is there any way to get entity Id after entity inserted in to database?
public override int Create<T>(T entity)
{
string entitySet = GetEntitySetName<T>();
_context.AddObject(entitySet, entity);
_context.SaveChanges();
return <Id Here>; //TODO Return Id here
}
在简单(非通用)存储库中,我可能只是返回Entity.Id,但是如何在通用存储库中获得相同的行为?
我可以为包含int属性ID的所有实体提供基本实体类,但是有没有办法在不实现该继承的情况下得到它?
In simple(not generic) repository i may just return Entity.Id, but how to get the same behavior in generic repository? I may have base entity class for all entities which contains int property Id but is there any way to get it work without implementing this inheritance?
推荐答案
解决方案:
public override TR Create<T, TR>(T entity)
{
string entitySet = GetEntitySetName<T>();
_context.AddObject(entitySet, entity);
_context.SaveChanges();
//Returns primaryKey value
return (TR)context.CreateEntityKey(entitySet, entity).EntityKeyValues[0].Value;
}
其中T:实体类型,TR:实体PK类型。
Where T: entity type, TR: entity PK type.
这篇关于EF通用存储库从新插入的通用实体获取Id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!