C# 具有nHibernate的通用存储库
我目前有这个类来弥补我的通用存储库C# 具有nHibernate的通用存储库,c#,asp.net-mvc,nhibernate,generics,repository,C#,Asp.net Mvc,Nhibernate,Generics,Repository,我目前有这个类来弥补我的通用存储库 public abstract class RepositoryBase<T> where T : class { private readonly ISession session; public RepositoryBase(ISession session) { this.session = session; this.session.FlushMode = FlushMode.Aut
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();
}
}
公共抽象类RepositoryBase,其中T:class
{
专用只读会话;
公共存储库(ISession会话)
{
this.session=会话;
this.session.FlushMode=FlushMode.Auto;
}
公开作废开始()
{
this.session.BeginTransaction();
}
公共布尔添加(T实体)
{
此.session.Save(实体);
返回true;
}
公共bool AddAll(IEnumerable items)
{
foreach(项目中的T项目)
{
此.session.Save(项目);
}
返回true;
}
公共布尔更新(T实体)
{
this.session.Flush();
此.session.Update(实体);
返回true;
}
公共布尔删除(T实体)
{
此.session.Delete(实体);
返回true;
}
公共bool DeleteAll(IEnumerable实体)
{
foreach(实体中的T实体)
{
本条删除(实体);
}
返回true;
}
公共T GetById(int-id)
{
返回此.session.Get(id);
}
公共T GetById(字符串id)
{
返回此.session.Get(id);
}
公共T GetById(长id)
{
返回此.session.Get(id);
}
公共T GetById(Guid id)
{
返回此.session.Get(id);
}
公共IQueryable GetAll()
{
返回此.session.Query();
}
公共T获取(表达式)
{
返回GetMany(表达式).SingleOrDefault();
}
公共IQueryable GetMany(表达式)
{
返回GetAll().Where(表达式).AsQueryable();
}
}
当我调用获取字符串参数的GetById方法时,遇到一个异常错误,该错误表示GetById需要的是类型Guid而不是字符串。如何设计此方法以接受字符串参数?您可以设计类,为id类型添加另一个通用参数:
public abstract class Repository<T, TId>
{
public T Get(TId id)
{
}
}
公共抽象类存储库
{
公用电话号码(TId id)
{
}
}
看看这个您可以设计您的类,为id类型添加另一个通用参数:
public abstract class Repository<T, TId>
{
public T Get(TId id)
{
}
}
公共抽象类存储库
{
公用电话号码(TId id)
{
}
}
看看这个