如何使用.Select()在.NET中映射具有不同类型列表属性的对象

问题描述 投票:0回答:1

我正在使用 .NET 7 并且我有一个需要映射到此 DTO 的实体框架查询:

public record MachineScheduleDataDto
{
   public int MachineScheduleId { get; set; }
   public required ICollection<MachineOperationDto> MachineOperationsDto { get; set; }
}

我的问题是,我不知道如何映射

MachineOperationsDto
属性,一旦它是 ICollection 并且具有与映射它的类不同的类型。

EF查询:

var test = _typedContext
    .AsNoTracking()
    .Include(m => m.MachineOperations!
        .Where(m =>
            m.InsertedAt.Date <= endDate.Date &&
            m.EndTime <= endDate.TimeOfDay &&
            m.InsertedAt.Date >= startDate.Date &&
            m.StartTime >= startDate.TimeOfDay))
    .ThenInclude(m => m.EggQuantities)
    .Where(m =>
        diffDays.Contains(m.WeekDay) &&
        m.MachineOperations!.Any() &&
        m.InitialProductionTime <= startDate.TimeOfDay &&
        m.FinalProductionTime >= startDate.TimeOfDay)
    .OrderBy(m => m.MachineScheduleId)
    .Select(m => new MachineScheduleDataDto
    {
        MachineScheduleId = m.MachineScheduleId,
        MachineOperationsDto = // Error because m.MachineOperation has the type "MachineOperation" and the MachineOperationsDto has the type "MachineOperationDto"
    });

我将用来制作地图的模型:

public class MachineOperation : BaseModel
{
    public int MachineOperationId { get; set; }
    public EMachineStatus MachineStatus { get; set; }
    public EDevStatus DevStatus { get; set; }
    public TimeSpan StartTime { get; set; }
    public TimeSpan EndTime { get; set; }

    #region Relationships

    public required virtual MachineSchedule MachineSchedule { get; set; }

    #endregion
}

DTO:

public record MachineOperationDto
{
    public int MachineOperationId { get; set; }
    public EMachineStatus MachineStatus { get; set; }

    public virtual required MachineScheduleDataDto MachineScheduleDto { get; set; }
}

PS:我无法使用 AUTOMAPPER,因为包含项内的过滤器被 AUTOMAPPER 忽略,请参阅此处

c# .net linq select mapper
1个回答
0
投票

通过

Select

投影一切
var test = _typedContext
    .Where(m =>
        diffDays.Contains(m.WeekDay) &&
        m.MachineOperations!.Any() &&
        m.InitialProductionTime <= startDate.TimeOfDay &&
        m.FinalProductionTime >= startDate.TimeOfDay)
    .OrderBy(m => m.MachineScheduleId)
    .Select(m => new MachineScheduleDataDto
    {
        MachineScheduleId = m.MachineScheduleId,
        MachineOperationsDto = m.MachineOperations!
            .Where(mo =>
                mo.InsertedAt.Date <= endDate.Date &&
                mo.EndTime <= endDate.TimeOfDay &&
                mo.InsertedAt.Date >= startDate.Date &&
                mo.StartTime >= startDate.TimeOfDay)
            .Select(mo => new MachineOperationDto
            {
                ... // other properties
            })
            .ToList()
    })
    .ToList();
© www.soinside.com 2019 - 2024. All rights reserved.