T4 模板中的存储库
我正在为存储库编写 T4 模板。
假设我们有客户/订单/产品表。然后我们有 CustomerRepo、OrdersRepo 和 ProductsRepo。
为所有这些都提供一个通用的存储库是一个好习惯吗?
public partial class Repository
{
private IContext context;
public Repository()
{
_Product = new ProductRepo();
_Customer = new CustomerRepo();
}
public Repository(IContext context)
{
this.context = context;
_Product = new ProductRepo(context);
_Customer = new CustomerRepo(context);
}
private ProductRepo _Product;
public ProductRepo Product {
get { return _Product; }
}
// Product
private CustomerRepo _Customer;
public CustomerRepo Customer {
get { return _Customer; }
}
// Customer
}
I am writing a T4 template for repositories.
Say we have Customers/Orders/Products tables. We then have CustomerRepo, OrdersRepo, and ProductsRepo.
Is it a good practice to have a generic repo for all of them?
public partial class Repository
{
private IContext context;
public Repository()
{
_Product = new ProductRepo();
_Customer = new CustomerRepo();
}
public Repository(IContext context)
{
this.context = context;
_Product = new ProductRepo(context);
_Customer = new CustomerRepo(context);
}
private ProductRepo _Product;
public ProductRepo Product {
get { return _Product; }
}
// Product
private CustomerRepo _Customer;
public CustomerRepo Customer {
get { return _Customer; }
}
// Customer
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现最好为每种类型创建一个存储库,而不是一个单一的存储库。否则,随着各种功能的添加,存储库往往会变得很大。
I find that it is best to make a repository for each type rather than one single repository. Otherwise the repository tends to get large as all sorts of functionality is added.
您甚至可以像帖子一样查看实现您的存储库。您甚至可以扩展概念并实现通用,并拥有 IRepository其中 T:IEntity 然后有一个名为
BaseRepository
的基本实现。根据您对问题的补充,您可能想要使用工厂模式或外观模式或依赖注入(使用 Unity/StructureMap 容器)。这取决于它的复杂程度以及您的解决方案需要的灵活性。
You can even look at implementing your repository like this post. You can even extend the concept and implement generic and have
IRepository<T> where T:IEntity
and then have a base implementation calledBaseRepository<T>
.Based on your additions to the question you might want to use Factory Pattern or Facade Pattern or Dependency Injection (using Unity/StructureMap container). It depends on how complex it is and how flexible your solution needs to be.
我最近回顾了实体框架的存储库模式的一些实现,并发现 https://github.com/tugberkugurlu /GenericRepository (描述于http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle)
最先进。
如果您将使用 GenericRepository 基类,我看不到使用 t4 模板生成派生类有任何好处。
I've recently reviewed a few implementations of Repository pattern with Entity frameworks and found https://github.com/tugberkugurlu/GenericRepository ( described at http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle)
the most advanced.
If you will use GenericRepository base class, I don't see any benefits to generate derived classes using t4 template.