带有nHibernate的通用存储库

时间:2013-09-07 20:47:27

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

1 个答案:

答案 0 :(得分:4)

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

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

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