【发布时间】:2021-07-03 09:07:01
【问题描述】:
我正在使用 AutoMapper 开发 .Net core 3 Web API
我有一个客户实体和订单实体。我已经为下面的每个创建了 DTO
public partial class Customer
{
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
public class CustomerDto
{
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public partial class Order
{
public int OrderId { get; set; }
public int? CustomerId { get; set; }
public byte OrderStatus { get; set; }
public virtual Customer Customer { get; set; }
public virtual Staff Staff { get; set; }
public virtual Store Store { get; set; }
public virtual ICollection<OrderItem> OrderItems { get; set; }
}
}
public class OrderDto
{
public int OrderId { get; set; }
public int? CustomerId { get; set; }
public byte OrderStatus { get; set; }
}
现在在 CustomerRepository 我有一个函数可以返回客户数据并在下面的客户控制器中使用
public async Task<IActionResult> GetCustomers ()
{
var result = await _repo.GetCustomers();
return Ok(_mapper.Map<List<CustomerDto>>(result));
}
到目前为止一切正常。我想在客户存储库中添加一个函数来返回客户数据以及他/她的订单列表
我尝试通过在 CustomerDto 中添加一个列表如下,但这对我来说是另一个问题
public class CustomerDto
{
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<OrderDto> Orders { get; set; }
}
现在,当我调用操作 GetCustomers 时,它会在 json 中返回一个空的 List<OrderDto>,这是有道理的。但我不想那样。我只想返回客户数据。
但是对于新功能,我想返回客户数据和订单列表。现在怎么办?
我认为我们不应该为我们所做的不同 SQL 连接查询创建不同的 DTO。那么这里的方法是什么?
【问题讨论】:
标签: c# asp.net-web-api .net-core automapper dto