.net - Linq 2 Sql - 如何使用实体继承设计适当的存储库、 Controller 和 View 模型流程

标签 .net linq-to-sql orm repository repository-pattern

问题:我想知道人们在 ORM 中使用实体继承时实现什么类型的存储库和 Controller 设计/工作流程,在本例中为带有 MVC .NET 的 LINQ 2 SQL。

我有一个非常简单的层次结构,其中 Clothing 类(具体)继承自 Product(抽象类)。然而,这使设计变得相当复杂。为每个 Product 的具体实现创建一个存储库类是愚蠢的,因此我在“Product”存储库中使用 Product 作为参数类型和返回类型。 “但是,因此,我必须将 Product 类型转换为 Product 的具体实现(在从存储库请求之前或之后)。

我注意到的另一件事是,即使我确定了要转换的正确类型,我也必须定义 View 模型以传递给 Product 的每个具体实现的 View 。

如果这是需要做的,那就这样吧,但我对其他人的想法和/或经验感兴趣。

最佳答案

为了便于讨论,我们假设您的存储库界面如下所示:

 public interface IRepository<T>{
     T GetById(int id);
     IQueryable<T> All();
     void Add(T entity);
     void Remove(T entity);
 }

虽然您是正确的,但为每个 Product 实现一个存储库是正确的type 是不必要的,您可以创建一个通用包装类来实现该接口(interface),就好像它是一个专用存储库一样。例如,

 public class RepositoryWrapper<T,TBase> : IRepository<T> {
     where T: TBase

     private readonly IRepository<TBase> _repository;
     public RepositoryWrapper(IRepository<TBase> repository){
           _repository = repository;
     }


     public T GetById(int id){
          return (T)_repository.GetById(id);
     }

     public IQueryable<T> All(){
          return _repository.All().OfType<T>();     
     }


     public void Add(T entity){
          _repository.Add(entity);
     }
     public void Remove(T entity){
          _repository.Remove(entity);
     }
 }

您的用例是RepositoryWrapper<Clothing,Product> ,并且您可以通过扩展方法来简化创建,例如:

public static class SubRepositories{
   public static IRepository<TDerived> GetSubClassRepository<TBase,TDerived>(this IRepository<TBase> repository)
   where TDerived: TBase
   {
       return new RepositoryWrapper<TDerived,TBase>(repository);
   }
}

现在,就 View 模型而言,在将 View 模型传递到 Controller 时不需要指定 View 模型的确切类型。另一种选择是 use templates to automatically determine the type of view to render based on the ModelMetadata .

关于.net - Linq 2 Sql - 如何使用实体继承设计适当的存储库、 Controller 和 View 模型流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6350704/

相关文章:

c# - 数据库设计头脑 Storm : Sale Prices

python - 将 SQL 命令转换为 Python 的 ORM

c# - 如何在本地网络中获取 IP 地址及其具有设备 MAC 的 http 端口

.net - .net Framework 4 中的 FileSystemWatcher 有多可靠?

.net - 我可以强制 MSTest 为每次测试运行使用新进程吗?

c# - excel 2010和2013中的数据模型//数据检索

c# - Linq 查询在本地机器上运行良好,但在服务器上出现 "The connection was reset"错误

visual-studio-2008 - 是否可以通过脚本自动生成我的 Linq2Sql DBML?

swift - 在数据库中实现[用户-订阅/订阅者]关系的最佳方法

hibernate - Hibernate 二级缓存的解决方案