0

我正在使用 EF Core,并且两个表之间存在多对多关系。

 public class Sale
    {
        public int Id { get; set; }
        public DateTime Date { get; set; }
        public double Total { get; set; }
        public List<SalePaymentMethod> SalePaymentMethods { get; set; }
    }

加入表:

    public class SalePaymentMethod
{
    public int DefferedPaymentCount { get; set; }
    public int SaleId { get; set; }
    public Sale Sale { get; set; }
    public double Amount { get; set; }
    public int PaymentMethodId { get; set; }
    public PaymentMethod PaymentMethod { get; set; }
}

关系的另一个表:

public class PaymentMethod
{
    public int Id { get; set; }
    public string PaymentName { get; set; }
    public bool PaymentType { get; set; }
    public List<SalePaymentMethod> SalePaymentMethods { get; set; }

}

我可以使用 AutoMapper 获得如下所示的扁平对象吗?

public class SaleUserBranchProductsDTO
{
    public int Id { get; set; }
    public DateTime Date { get; set; }
    public double Total { get; set; }
    public List<PaymentMethodDto> PaymentMethods { get; set; }
}

PaymentMethodDto 是:

public class PaymentMethodDto
{
    public string PaymentName { get; set; }
    public bool PaymentType { get; set; }
    public int DefferedPaymentCount { get; set; }
    public double Amount { get; set; }
}

我的问题可能是我想在主映射中进行另一个映射。

4

1 回答 1

0

我想出了如何解决它。

创建配置文件以映射SalePaymentMethodPaymentMethodDto

    public class PaymentMethodProfile : Profile
{
    public PaymentMethodProfile()
    {
        CreateMap<SalePaymentMethod, PaymentMethodDto>()
             .ForMember(q => q.Amount, opt => opt.MapFrom(s => s.Amount))
             .ForMember(q => q.DefferedPaymentCount, opt => opt.MapFrom(s => s.DefferedPaymentCount))
             .ForMember(q => q.PaymentName, opt => opt.MapFrom(s => s.PaymentMethod.PaymentName))
             .ForMember(q => q.PaymentType, opt => opt.MapFrom(s => s.PaymentMethod.PaymentType));


    }
}

创建另一个配置文件以将表单映射SaleSaleUserBranchProductsDTO

public SaleUserBranchProductsProfile()
{
    CreateMap<Sale, SaleUserBranchProductsDTO>()
        .ForMember(q => q.Id, opt => opt.MapFrom(s => s.Id))
        .ForMember(q => q.Date, opt => opt.MapFrom(s => s.Date))
        .ForMember(q => q.Total, opt => opt.MapFrom(s => s.Total))
        //Here is the magic
        .ForMember(q=> q.PaymentMethoddtos, opt => opt.MapFrom(s => s.SalePaymentMethods));
}

}

然后像这样使用它:

 _mapper.ProjectTo<SaleUserBranchProductsDTO>(_context.Sales.Where(wh => wh.UserId == UserId)).ToList();
于 2020-02-08T15:52:08.480 回答