【发布时间】:2016-10-04 20:18:13
【问题描述】:
试图弄清楚在使用通用存储库模式时如何获取最近添加的实体的 ID。一个例子会很好。 这是存储库,
public class Repository<T> : IRepository<T> where T : class {
protected DbContext DbContext { get; set; }
protected DbSet<T> DbSet { get; set; }
public Repository(DbContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException("dbContext");
DbContext = dbContext;
DbSet = DbContext.Set<T>();
}
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State == EntityState.Detached)
{
DbSet.Attach(entity);
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
}
}
entity.Id 不存在这里
【问题讨论】:
-
当您添加实体时,其
Id属性将被填充。你应该提供一些代码。 -
我包含了 Generic Repository 类
标签: c# generics design-patterns repository entity-framework-5