Generic Repository with nHibernate

2019-05-20 05:42发布

I currently have this class make up for my Generic 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();
    }
}

When I call the GetById method which takes a string parameter I am met with an exception error that states GetById is expecting type Guid not string. How do I design this method to accept a string parameter?

1条回答
你好瞎i
2楼-- · 2019-05-20 06:26

You can design your class adding another generic parameter for the type of id:

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

take a look at this https://github.com/sharparchitecture/sharp-architecture/wiki

查看更多
登录 后发表回答