EF4: how to use a generic repository pattern ?

99封情书 提交于 2019-12-05 18:39:10
dan radu

You can have a generic expression parameter for your GetSingle method:

public interface IRepository<T> : IDisposable where T : class
{
    ....
    T GetSingle(Expression<Func<T, bool>> filter);
    void Save(T entity);
}

and in HGRepository<T>:

public T GetSingle(Expression<Func<T, bool>> filter)
{
        return _objectSet.Where(filter).SingleOrDefault();
}

And usage:

IRepository<Article> rep = new HGRepository<Article>();
return rep.GetSingle(p => p.Slug == slug);

If you have particular scenarios which the generic interface / repository class don't cover, you can create new interface / class which inherit from the generic ones:

public interface IArticleRepository : IRepository<Article>
{
   ...
}

public class ArticleRepository : HGRepository<Article>, IArticleRepository
{
   ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!