本文介绍了如何在实体框架通用插入方法中返回插入记录的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是通用的插入方法。我需要您的建议以返回插入记录的ID。
Here is the generic insert method. I need your suggestion to return the ID of the inserted record.
public static void Create<T>(T entity) where T : class { using (var context = new InformasoftEntities()) { DbSet dbSet = context.Set<T>(); dbSet.Add(entity); context.SaveChanges(); } }推荐答案
您需要做一些修改:
您需要创建由实体实现的IHasAutoID
You need to create an IHasAutoID that implemented by Entity public interface IHasAutoID { int getAutoId(); }
在实体类中
In Entity Class
public class EntityA : IHasAutoID { public int getAutoId() { return pk; // Return -1 If the entity has NO Auto ID } }
在您的Create函数中
In your Create function
public static int Create<T>(T entity) where T : class { using (var context = new InformasoftEntities()) { DbSet dbSet = context.Set<T>(); dbSet.Add(entity); context.SaveChanges(); if (entity is IHasAutoID) { return ((IHasAutoID)entity).getAutoId(); } return -1; // entity is NOT IHasAutoID) } }
注意:
NOTES:
- 如果您确定所有表都具有名为 Id的自动ID。您无需创建接口IHasAutoID。在Create函数中,在SaveChanges之后,您可以使用REFLECTION获取Id属性的值,但是不建议这种方式!
更多推荐
如何在实体框架通用插入方法中返回插入记录的ID?
发布评论