我對這個存儲庫模式不熟悉。存儲庫中有以下方法。使用存儲庫模式獲取上次插入的行ID
public abstract class Repository<T> : IRepository<T> where T : class
{
private PHOnlineEntities dataContext;
private readonly IDbSet<T> dbset;
protected Repository(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
dbset = DataContext.Set<T>();
}
protected IDatabaseFactory DatabaseFactory
{
get;
private set;
}
protected PHOnlineEntities DataContext
{
get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
}
public virtual int Add(T entity)
{
dbset.Add(entity);
dataContext.SaveChanges();
// return id here
}
public virtual void Update(T entity)
{
dbset.Attach(entity);
dataContext.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
dbset.Remove(entity);
}
public virtual void Delete(Expression<Func<T, bool>> where)
{
IEnumerable<T> objects = dbset.Where<T>(where).AsEnumerable();
foreach (T obj in objects)
dbset.Remove(obj);
}
public virtual T GetById(long id)
{
return dbset.Find(id);
}
public virtual T GetById(string id)
{
return dbset.Find(id);
}
public virtual IEnumerable<T> GetAll()
{
return dbset.ToList();
}
public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
{
return dbset.Where(where).ToList();
}
public T Get(Expression<Func<T, bool>> where)
{
return dbset.Where(where).FirstOrDefault<T>();
}
這是我CustomerRepository類
public interface ICustomerDetailRepository : IRepository<CustomerDetail>
{
}
/// <summary>
/// CustomerDetail repository
/// </summary>
public class CustomerDetailRepository : Repository<CustomerDetail>, ICustomerDetailRepository
{
/// <summary>
///
/// </summary>
private PHOnlineEntities _dataContext;
/// <summary>
///
/// </summary>
protected IDatabaseFactory DatabaseFactory
{
get;
private set;
}
/// <summary>
///
/// </summary>
/// <param name="databaseFactory"></param>
public CustomerDetailRepository(IDatabaseFactory databaseFactory)
: base(databaseFactory)
{
DatabaseFactory = databaseFactory;
}
/// <summary>
///
/// </summary>
protected PHOnlineEntities DataContext
{
get { return _dataContext ?? (_dataContext = DatabaseFactory.Get()); }
}
}
爲CustomerDetail類包含模型。它具有所有實體列和ID列。
當我添加實體到數據庫,我想返回最後插入的行ID。 Id是標識列。任何人都可以幫助我嗎?
是的。由於我們正在使用通用庫類,因此我在CustomerRepository中添加了Override Add函數。這解決了我的問題。謝謝 :) – PaRsH