如何使用 Automapper 将对象投影到 LINQ 中的 Dto

How to use Automapper to project object to Dto in LINQ

我正在研究 .NET Core 6 和 EF Core。我想使用 ProjectTo.

将 LINQ select 中的 CustomerOrder 对象转换为 CustomerDtoOrderDto

使用库

using AutoMapper;
using AutoMapper.QueryableExtensions;

我知道如何使用此处显示的代码映射 IQueryable

var x = (from customer in db.Customers
         where customer.CustomerId == CustomerId
         select customer).ProjectTo<CustomerDto>(_mapper.ConfigurationProvider);

但我不确定如何在 new 中投影,或者是否应该以不同的方式进行投影?下面是我希望客户 CustomerDto & OrderOrderDto

的 LINQ 代码
var customerOrdersQuery =
            (from customer in db.Customers.Where(x => x.CustomerId == CustomerId)
             join orders in db.Orders on customer.CustomerId equals orders.CustomerId into cst_Ord
             from customerOrders in cst_Ord.DefaultIfEmpty()
             select new { 
                 customer,        //ProjectTo<CustomerDto>
                 customerOrders   //ProjectTo<OrderDto>
             }).AsEnumerable();

A​​faik 您需要一个中介 class CustomerWithOrdersSource,您使用 Automapper 的 ProjectTo 将其映射到 CustomerWithOrdersDto。

映射

public class CustomerWithOrdersSource
{
   public Customer Customer {get;set;}
   public ICollection<Order> Orders {get;set;}
}
public class CustomerWithOrdersDto
{
   public CustomerDto Customer {get;set;}
   public ICollection<OrderDto> Orders {get;set;}
}
CreateMap<CustomerWithOrdersSource, CustomerWithOrdersDto>();

查询

var customerOrdersQuery =
            (from customer in db.Customers.Where(x => x.CustomerId == CustomerId)
             join orders in db.Orders on customer.CustomerId equals orders.CustomerId into cst_Ord
             from customerOrders in cst_Ord.DefaultIfEmpty()
             select new CustomerWithOrdersSource() { 
                 Customer = customer,
                 Orders = customerOrders
             }).ProjectTo<CustomerWithOrdersDto>(_mapper.ConfigurationProvider);

编辑:根据@Lucian Bargaoanu 的说法,您也可以直接从匿名对象进行投影。但是,如果以后需要,您可以通过编辑映射配置文件轻松自定义映射。