Entity framework 如何在实体框架通用插入方法中返回插入记录的ID?
下面是通用的insert方法。我需要你的建议返回插入记录的IDEntity framework 如何在实体框架通用插入方法中返回插入记录的ID?,entity-framework,generics,Entity Framework,Generics,下面是通用的insert方法。我需要你的建议返回插入记录的ID public static void Create<T>(T entity) where T : class { using (var context = new InformasoftEntities()) { DbSet dbSet = context.Set<T>(); dbSet.Add(entity); context.SaveChan
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();
}
}
publicstaticvoidcreate(T实体),其中T:class
{
使用(var context=newinformationsoftenties())
{
DbSet DbSet=context.Set();
添加(实体);
SaveChanges();
}
}
您需要稍作修改:
公共接口IHasAutoID{
int getAutoId();
}
public class EntityA : IHasAutoID {
public int getAutoId() {
return pk; // Return -1 If the entity has NO Auto ID
}
}
公共静态int-Create(T实体),其中T:class
{
使用(var context=newinformationsoftenties())
{
DbSet DbSet=context.Set();
添加(实体);
SaveChanges();
if(实体为IHasAutoID){
返回((IHasAutoID)实体).getAutoId();
}
return-1;//实体不是IHasAutoID)
}
}
- 如果您确定所有表都具有名为“ID”的自动ID。您不需要创建接口IHasAutoID。在Create函数中,在SaveChanges之后,您可以使用反射来获取Id属性的值,但不推荐使用这种方式李>
阿图罗·马丁内克斯的评论是正确的 实体框架在SaveChanges期间修复了ID,因此它已经在传递给方法的实体中更新 要具体执行您的要求,您可以将泛型约束从类更改为所有实体继承的新抽象类,该抽象类定义该类中的键
public static int Create<T>(T entity) where T : BaseEntity
{
using (var context = new InformasoftEntities())
{
DbSet dbSet = context.Set<T>();
dbSet.Add(entity);
context.SaveChanges();
return entity.Id;
}
}
public abstract class BaseEntity
{
int Id { get; set;}
}
公共静态int-Create(T-entity),其中T:BaseEntity
{
使用(var context=newinformationsoftenties())
{
DbSet DbSet=context.Set();
添加(实体);
SaveChanges();
返回实体Id;
}
}
公共抽象类BaseEntity
{
int Id{get;set;}
}
这种技术在InsertOrUpdate
方法中更有用
在泛型方法中使用键的另一种方法是查询元数据,如下所述:
公共异步任务添加(TEntity实体)
{
wait_context.Set().AddAsync(实体);
等待保存();
返回Task.FromResult(entity).Id;
}
调用SaveChanges()
后,它应该在您的实体中自动更新。换句话说,您不需要返回它。所有表都有名为“Id”且类型为“int”的PK。测试我的解决方案。它适用于所有类型的实体(是否具有自动ID)。此技术与我的技术相同。抽象类与接口。看起来更简单,但我已经选择了Loc的解决方案。非常感谢。假设所有实体都有一个名为“Id”的键属性!虽然这段代码可以解决这个问题,但如何以及为什么解决这个问题将真正有助于提高您的帖子质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请您在回答中添加解释,并说明适用的限制和假设。抱歉,这是一份不准确的汇编。1.实体框架没有Save
方法。2.具有该名称的方法看起来不像是可以等待的。3.完全没有理由使用Task.FromResult
。4.谁说tenty
有Id
属性?好吧,至少编译器没有,那是负责人。最后一个错误足以使这个答案无效。
public async Task<int> Add(TEntity entity)
{
await _context.Set<TEntity>().AddAsync(entity);
await Save();
return Task.FromResult(entity).Id;
}