EF Generic Repository从新插入的通用实体获取Id

我的所有实体都有财产ID。 数据库中的所有表都将自动生成的整数标识Id作为主键。

我有创建实体的通用方法。

有没有办法在实体插入数据库后获取实体ID?

public override int Create(T entity) { string entitySet = GetEntitySetName(); _context.AddObject(entitySet, entity); _context.SaveChanges(); return ; //TODO Return Id here } 

在简单(非通用)存储库中,我可能只返回Entity.Id,但如何在通用存储库中获得相同的行为? 我可能有包含int属性Id的所有实体的基本实体类,但有没有办法让它工作而不实现这种inheritance?

这实际上可能很简单;

 // Project is is object/table, no POCO here. var newProj = new Project(); newProj.Name = "Blah project"; var db = new AppDataContextname(); db.Projects.AddObject(newProj); // at this point, newProj.ID is NOT set db.SaveChanges(); // record is added to db. // now, the ID property of the Project object is set!!! // if the last ID in that table is '25', and you have auto-increment, // then the object's ID property will now be 26! Console.WriteLine(newProj.ID); // will output "26" 

在我意识到上面的代码有效之前,我已经知道了如何将ID恢复很长时间。 适用于Linq-To-SQL和EF4。

使用POCO实体,您必须使用界面,reflection或dynamic

使用EntityObject实体,您可以读取EntityKey属性。

解决方案:

  public override TR Create(T entity) { string entitySet = GetEntitySetName(); _context.AddObject(entitySet, entity); _context.SaveChanges(); //Returns primaryKey value return (TR)context.CreateEntityKey(entitySet, entity).EntityKeyValues[0].Value; } 

其中T:实体类型,TR:实体PK类型。

  With reflection you can obtain the Id property. public override int Create(T entity) { string entitySet = GetEntitySetName(); _context.AddObject(entitySet, entity); _context.SaveChanges(); var idProperty = item.GetType().GetProperty("Id").GetValue(entity,null); return (int)idProperty; }