【问题标题】:Generic Repository with nHibernate使用 nHibernate 的通用存储库
【发布时间】:2013-09-07 20:47:26
【问题描述】:

我目前有这个类来弥补我的通用存储库

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 而不是字符串。如何设计此方法以接受字符串参数?

【问题讨论】:

    标签: c# asp.net-mvc nhibernate generics repository


    【解决方案1】:

    您可以设计您的类,为 id 类型添加另一个通用参数:

    public abstract class Repository<T, TId>
    {
        public T Get(TId id)
        {
        }
    }
    

    看看这个https://github.com/sharparchitecture/sharp-architecture/wiki

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多