如何解决问题,与映射值从其他表的外键?我有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; }
}
现在的响应看起来像这样:({"id" 1、"warranty"3","description"aaaa"clientId" 1、})
是否可以通过外键从其他表中获取值?例如,我希望输出如下:
[
{
"id": 1,
"warranty": "3",
"description": "aaaa",
"client":{"ClientId": 1, "Name": Example, "Surname": Example, "Phone": 1234567
}
]
我认为有以下的东西会帮助你。基本上,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; }
}
在AutoMapper
CreateMap<Repair, RepairReadDto>()..ReverseMap();
CreateMap<Client, ClientDto>()..ReverseMap();
好的,现在如果我使用两个不同的表(客户端,修复),我需要在每个表上导入存储库并填充"客户端";from Repair in controller.
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);
}
还有其他约定吗?