【问题标题】:Mapping one DTO to multiple entities将一个 DTO 映射到多个实体
【发布时间】:2013-08-26 14:09:46
【问题描述】:

我有如下的数据库模型。这里我描述了我在 EF 模型中的实体:

   public class Person
   {
      public int Id { get; set; }
      public int AddressId { get; set; }
      public int RoleId { get; set; }
      public string Name { get; set; }
      public string Email { get; set; }
   }

   public class Address
   {
      public int Id { get; set; }
      public int CountryId { get;set; }
      public string City { get; set; }
   }

   public class Role
   {
      public int Id { get; set; }
      public string Name { get; set; }
   }

   public class Country
   {
      public int Id { get; set; }
      public string Name { get; set; }
   }

在前端我有允许编辑用户信息的管理界面。 因此,在每条网格线中,我都显示了以下 DTO 对象:

   public class SystemUser
   {
      public string UserName { get; set; }
      public string Email { get; set; }
      public string City { get; set; }
      public string Country { get; set; }
      public string Role { get; set; }
   }

我的主要问题 - 在执行编辑后将其映射回实体的最佳方法是什么,我使用 AutoMapper 或其他东西取回 DTO?

或者我在这里做了什么完全愚蠢的事情?

编辑: 我还有另一个挑战:我想尽量减少到数据库的往返次数。

【问题讨论】:

    标签: entity-framework domain-driven-design automapper dto


    【解决方案1】:

    我发现AutoMapper 是创建我的视图模型等的绝佳选择。保存时我发现使用带有Save(SystemUser user) 等方法的服务类是最好的,因为这样您就有空间控制验证和其他必须的事情做完了。用于创建您需要保存的实体的映射代码是手工完成的,因为通常保存中涉及的因素比读取中涉及的因素多得多。因此AutoMapper 在这里不是一个好的选择。我通常用它的构造函数中的各种实体的存储库来编写我的服务类。这更多的是允许您没有提到的单元测试,但无论如何都是一个好的设计。如果这是您需要的那种东西,那么我认为您在正确的轨道上。

    【讨论】:

    • 接受这个作为答案。但是,我能够实现自己的映射引擎,最能满足我的要求。
    • @Alexander Efimov - 我很想看看您的映射解决方案,因为这是一个常见问题。
    • @ChrisM。它是一种基于表达式的解决方案,但非常有限,例如不支持内部对象构建。最终,它变成了一种框架。但回到我最初的问题——目前我们正在读取 EDMX 文件以提取数据库、表和列名称并从中生成帮助程序类。基于映射配置,我们动态构建 SQL 的类知道 SystemUser 对象映射到 Person、Address、Role 和 Country。这将生成 4 条 SQL 语句,用于最后的必要操作。因此,我们使用 EF 读取,但使用我们自己的实现保存。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多