2

在 .NET Core 2.X 中,我可以使用以下代码:

var bookings = await db.Tasks
        .Where(c => c.ClientId == clientId && c.IsDeleted == false && c.Start > startOfThisMonth && c.End < endOfThisMonth)
        .OrderBy(x => x.Start)
        .Select(x => new SpecialTaskVm(new TaskViewModel(x, null))
        {
            client = x.Client,
            carer = x.Booking.SingleOrDefault(b => b.SlotNumber == 1).Carer,
            carer2 = x.Booking.SingleOrDefault(bk => bk.SlotNumber == 2).Carer
        })
        .ToListAsync();

但是 .net core 3.X 中的相同代码会导致此错误:

System.InvalidOperationException:从“VisitMemberInit”调用时,重写“System.Linq.Expressions.NewExpression”类型的节点必须返回相同类型的非空值。或者,覆盖“VisitMemberInit”并将其更改为不访问这种类型的孩子。

我真的可以按照上面的方式进行选择,因为每个模型都对某些属性进行了一些修改,并且每个模型都在其他地方单独使用。

我也试图避免 a foreach,因为它似乎效率低下。

我尝试将需要设置的属性传递到模型中,然后像这样在模型中设置它们。发生同样的错误。

//This action method will return data for current month.
var startOfThisMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
var endOfThisMonth = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(1).Month, 1);

var bookings = await db.Tasks
        .Where(c => c.ClientId == clientId && c.IsDeleted == false && c.Start > startOfThisMonth && c.End < endOfThisMonth)
        .OrderBy(x => x.Start)
        .Select(x => new SpecialTaskVm(new TaskViewModel(x, null))
        {
            client = x.Client,
            carer = x.Booking.SingleOrDefault(b => b.SlotNumber == 1).Carer,
            carer2 = x.Booking.SingleOrDefault(bk => bk.SlotNumber == 2).Carer
        })
        .ToListAsync();

List<SpecialTaskVm>我希望任务列表以withClient和setCarer的形式返回。Carer2

4

1 回答 1

3

在同一代码中使用构造函数和对象初始化语法有点不寻常,对我来说这已经是一种代码味道。

如果我是你,我会创建一个只从数据库中获取值的中间列表,然后将该数据投影到你的SpecialTaskVm对象中。例如:

// First get the data from the database in a simple form we can parse through later
var bookingData = await db.Tasks
        .Where(c => c.ClientId == clientId && c.IsDeleted == false && c.Start > startOfThisMonth && c.End < endOfThisMonth)
        .OrderBy(x => x.Start)
        .Select(x => new // Use an anonymous type
        {
            Client = x.Client,
            Carer = x.Booking.SingleOrDefault(b => b.SlotNumber == 1).Carer,
            Carer2 = x.Booking.SingleOrDefault(bk => bk.SlotNumber == 2).Carer
        })
        .ToListAsync();

// Now we massage the data into a format we can use
var bookings = bookingData
        .Select(x => new SpecialTaskVm(new TaskViewModel(x, null))
        {
            client = x.Client,
            carer = x.Carer,
            carer2 = x.Carer2
        })
        .ToList();

此外,我可能会建议更改SpecialTaskVm构造函数(或添加新构造函数)以包含新字段。

于 2019-09-10T18:53:23.490 回答