具有 nHibernate 的通用存储库
本文关键字:存储 nHibernate 具有 | 更新日期: 2023-09-27 18:30:42
我目前有这个类为我的通用存储库组成
public abstract class RepositoryBase<T> where T : class
{
private readonly ISession session;
public RepositoryBase(ISession session)
{
this.session = session;
this.session.FlushMode = FlushMode.Auto;
}
public void Start()
{
this.session.BeginTransaction();
}
public bool Add(T entity)
{
this.session.Save(entity);
return true;
}
public bool AddAll(IEnumerable<T> items)
{
foreach (T item in items)
{
this.session.Save(item);
}
return true;
}
public bool Update(T entity)
{
this.session.Flush();
this.session.Update(entity);
return true;
}
public bool Delete(T entity)
{
this.session.Delete(entity);
return true;
}
public bool DeleteAll(IEnumerable<T> entities)
{
foreach (T entity in entities)
{
this.Delete(entity);
}
return true;
}
public T GetById(int id)
{
return this.session.Get<T>(id);
}
public T GetById(string id)
{
return this.session.Get<T>(id);
}
public T GetById(long id)
{
return this.session.Get<T>(id);
}
public T GetById(Guid id)
{
return this.session.Get<T>(id);
}
public IQueryable<T> GetAll()
{
return this.session.Query<T>();
}
public T Get(Expression<System.Func<T, bool>> expression)
{
return GetMany(expression).SingleOrDefault();
}
public IQueryable<T> GetMany(Expression<System.Func<T, bool>> expression)
{
return GetAll().Where(expression).AsQueryable();
}
}
当我调用采用字符串参数的 GetById 方法时,我遇到了异常错误,指出 GetById 需要类型 Guid 而不是字符串。如何设计此方法以接受字符串参数?
您可以在设计类时为 id 类型添加另一个泛型参数:
public abstract class Repository<T, TId>
{
public T Get(TId id)
{
}
}
看看这个 https://github.com/sharparchitecture/sharp-architecture/wiki