[英]Repository Pattern: Dealing with Identical Repositories
I have four very similar but hierarchical entities. 我有四个非常相似但层次分明的实体。 Each one has a foreign key to the previous and contains collections of the next ones.
每个都有一个以前的外键,并包含下一个的集合。
Right now, these entities have four identical repositories: 现在,这些实体有四个相同的存储库:
The implementations of the two methods will differ slightly for each. 两种方法的实现方式各有所不同。
Is there a design pattern that will allow me to merge all four into one while at the same time allowing me to extend functionality if needed ? 是否有一种设计模式允许我将所有四个合并为一个,同时允许我在需要时扩展功能 ?
I tried to do this: 我试着这样做:
public class DivisionRepository : IDivisionRepository
{
private DbContext dbContext;
private IDbSet<PrimaryDivision> primaryDivisionsEntitySet;
private IDbSet<SecondaryDivision> secondaryDivisionsEntitySet;
private IDbSet<TertiaryDivision> tertiaryDivisionsEntitySet;
private IDbSet<QuaternaryDivision> quaternaryDivisionsEntitySet;
public DivisionRepository(DbContext dbContext)
{
this.dbContext = dbContext;
this.primaryDivisionsEntitySet = dbContext.Set<PrimaryDivision>();
this.secondaryDivisionsEntitySet = dbContext.Set<SecondaryDivision>();
this.tertiaryDivisionsEntitySet = dbContext.Set<TertiaryDivision>();
this.quaternaryDivisionsEntitySet = dbContext.Set<QuaternaryDivision>();
}
public IDivision Find(Type type, object id)
{
if (type == typeof(PrimaryDivision))
{
return this.primaryDivisionsEntitySet.Find(id);
}
else if (type == typeof(SecondaryDivision))
{
return this.secondaryDivisionsEntitySet.Find(id);
}
else if (type == typeof(TertiaryDivision))
{
return this.tertiaryDivisionsEntitySet.Find(id);
}
else if (type == typeof(QuaternaryDivision))
{
return this.quaternaryDivisionsEntitySet.Find(id);
}
throw new ArgumentException("The type provided was incorrect.");
} }
CRUD operations continue in similar fashion. CRUD操作以类似的方式继续。
However, it didn't seem like the most optimal solution, so I reverted back to the hodgepodge of interfaces and classes I have now (two per repository). 然而,它似乎不是最佳解决方案,所以我回到了我现在拥有的接口和类的大杂烩(每个存储库两个)。
Thank you 谢谢
I would do this using what I call a composable repository . 我会使用我称之为可组合的存储库来执行此操作。
public static T SpecialFind(this IQueryable<T> entities, int id) where T: IDivision
{
return entities.FirstOrDefault(x=>x.Id == id);
}
usage: 用法:
ctx.TertiaryDivisions.SpecialFind(1);
The benefit of doing this is that it gives really nice reuse patterns, especially with more complex scenarios. 这样做的好处是它提供了非常好的重用模式,特别是对于更复杂的场景。
however if you are absolutely set on a repository pattern the same basic principal applies: 但是,如果您完全设置在存储库模式上,则应用相同的基本主体:
public T Find<T>(object id) where T : IDivision
{
return dbContext.Set<T>().Find(id);
}
Alternately you could put the generic on the whole repository. 或者,您可以将泛型放在整个存储库中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.