EF4:如何使用一个通用存储库的模式? [英] EF4: how to use a generic repository pattern ?
问题描述
我试图用通用的回购我可以从子类来简化现有的回购协议。问题是,我无法弄清楚如何写我的几个基类的方法。我目前有:
I'm trying to streamline my existing repos by using a generic repo I can subclass from. The problem is that I can't figure out how to write a few of my base class methods. I currently have:
public interface IRepository<T> : IDisposable where T : class
{
IQueryable<T> GetAll();
T GetSingle(int id);
T GetSingle(string slug);
void Save(T entity);
}
public class HGRepository<T> : IRepository<T> where T : class
{
protected HGEntities _siteDB;
protected IObjectSet<T> _objectSet;
public HGRepository(HGEntities context)
{
_siteDB = context;
_objectSet = _siteDB.CreateObjectSet<T>();
}
public IQueryable<T> GetAll()
{
return _objectSet;
}
public T GetSingle(int id)
{
return null;
}
public T GetSingle(string slug)
{
return null;
}
public void Save(T entity)
{
// code to save entity
}
public void Dispose()
{
_siteDB = null;
}
}
我的困惑在于我的 GetSingle()
和保存()
方法。他们将需要依靠这与每种类型 T
的信息稍有不同。从我的非通用回购例如:
My confusion lies with my GetSingle()
and Save()
methods. They'll need to rely on information that's slightly different with each type of T
. Example from my non-generic repos:
public Article GetArticle(int id)
{
return _siteDB.Articles.SingleOrDefault(a => a.ArticleID == id);
}
public Article GetArticle(string slug)
{
return _siteDB.Articles.SingleOrDefault(a => a.Slug == slug);
}
public void SaveArticle(Article article)
{
if (article.ArticleID > 0)
{
_siteDB.ObjectStateManager.ChangeObjectState(article, System.Data.EntityState.Modified);
}
else
{
_siteDB.Articles.AddObject(article);
}
_siteDB.SaveChanges();
}
正如你所看到的,文章有自己的,特定的ID。我的其他实体同样的事情(新闻项目有一个NewSID的属性,例如)。
As you can see, Articles have their own, specific id. The same thing for my other entities (News items have a NewsID property, for instance).
我怎么能作出这样可以调和成一个更具体的版本,一个抽象基方法是什么?
How can I make an abstract base method that can be reconciled into a more specific version?
推荐答案
您可以有一个通用的前pression 您 GetSingle
方法的参数:
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);
}
和 HGRepository&LT; T&GT;
:
public T GetSingle(Expression<Func<T, bool>> filter)
{
return _objectSet.Where(filter).SingleOrDefault();
}
和用法:
IRepository<Article> rep = new HGRepository<Article>();
return rep.GetSingle(p => p.Slug == slug);
如果您有特殊的情况下该通用接口/ repository类不包括,你可以创建新的接口/类从一般的人继承:
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
{
...
}
这篇关于EF4:如何使用一个通用存储库的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!