Generic Repository. FindByID
I am playing around with making a nhibernate generic repo but I am unsure how to make a method to return an entity back by ID
public class NhibernateRepo : INhibernateRepo
{
private readonly ISession session;
public NhibernateRepo(ISession session)
{
this.session = session;
}
public void Create<T>(T entity)
{
session.Save(entity);
}
public void CreateOrUpdate<T>(T entity)
{
session.SaveOrUpdate(entity);
}
public void Delete<T>(T entity)
{
session.Delete(entity);
}
public void Update<T>(T entity)
{
session.Update(entity);
}
public T Get<T>(object id)
{
return session.Get<T>(id);
}
public T Load<T>(object id)
{
return session.Load<T>(id);
}
public void ReadOnly(object entity, bool readOnly = true)
{
session.SetReadOnly(entity, readOnly);
}
public void Evict(object ent开发者_运维问答ity)
{
session.Evict(entity);
}
public object Merge(object entity)
{
return session.Merge(entity);
}
public IEnumerable<T> FindAll<T>()
{
return session.Query<T>();
}
}
You can define this method in the repository interface:
interface IRepository<TEntity, TId> where TEntity : class {
TEntity FindById(TId id);
...
}
And following in repository implementation:
class Repository<TEntity, TId> : IRepository<TEntity, TId> where TEntity : class{
public TEntity FindById(TId id) {
return _session.Get<TEntity>(id);
}
}
As a side note, generic repository interface is sometimes considered to be a bad practice from Domain Driven Design perspective.
精彩评论