【问题标题】:AutoMapper - how to return values from foreign key?AutoMapper - 如何从外键返回值?
【发布时间】:2021-04-28 17:04:54
【问题描述】:

如何通过外键从其他表中映射值来解决问题?我有 2 个表(客户、维修)。

public class Repair
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Warranty { get; set; }

    [Required]
    public string Description { get; set; }

    [ForeignKey(nameof(Client))]
    public int ClientId { get; set; }
}

public class RepairReadDto
{
    public int Id { get; set; }

    public string Warranty { get; set; }

    public string Description { get; set; }

    public int ClientId { get; set; }
}

现在的响应如下所示: [ { “身份证”:1, “保修”:“3”, “描述”:“aaaa”, “客户标识”:1, } ]

可以通过外键从其他表中获取值吗?例如,我期望这样的输出:

[
    {
        "id": 1,
        "warranty": "3",
        "description": "aaaa",
        "client":{"ClientId": 1, "Name": Example, "Surname": Example, "Phone": 1234567
    }
]

【问题讨论】:

  • 是的,这是可能的。但是你没有提到你有问题吗?是在 AutoMapper 中还是在 EntityFramework 中?
  • 问题是我认为使用自动映射器,我的地图看起来像这样: CreateMap();我还需要做点什么吗?

标签: c# asp.net sql-server entity-framework automapper


【解决方案1】:

我认为以下内容会对您有所帮助。基本上,Auto Mapper 也可以映射子对象,但应该定义它并相应地创建类。

public class Repair
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Warranty { get; set; }

    [Required]
    public string Description { get; set; }

    [ForeignKey(nameof(Client))]
    public int ClientId { get; set; }

    public virtual Client Client { get; set; }
}

public class RepairReadDto
{
    public int Id { get; set; }

    public string Warranty { get; set; }

    public string Description { get; set; }

    public int ClientId { get; set; }

    public ClientDto Client { get; set; }
}

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

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

在自动映射器上

CreateMap<Repair, RepairReadDto>()..ReverseMap();
CreateMap<Client, ClientDto>()..ReverseMap();

【讨论】:

    【解决方案2】:

    好的,现在如果我使用两个不同的表(客户端,修复),我需要在每个表上导入存储库并从控制器中的修复中填写“客户端”。

    public ActionResault<IEnumerable<RepairReadDto>> GetRepairList()
    {
         var repairList = _repairRepo.GetProductList().Tolist();
         foreach(var repair from repairList)
         {
            repair.Client = _mapper.Map<ClientReadDto>(_clientRepo.GetClientById(repair.ClientId))
         }
         
         return Ok(repairList);
    }
    

    还有其他约定吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多