EF Core 3.0和OrderBy在Automapper Project发布后

时间:2019-11-26 10:45:47

标签: c# entity-framework-core automapper

尝试在类属性内的列上排序时,我在EF Core 3上使用Automappers ProjectTo遇到错误。

public class CustomerDto
{
    public string Name { get; set; }
    public SettingsDto Settings { get; set; }
}

public class SettingsDto
{
    public int VoucherStartNum { get; set; }
}

var mapperCfg = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Customer, CustomerDto>();
    cfg.CreateMap<CustomerSettings, SettingsDto>();
});

// This is working.
var workingSelect = _db.Customer
    .Select(x => new CustomerDto
    {
        Name = x.Name, 
        Settings = new SettingsDto
        {
            VoucherStartNum = x.Settings.VoucherStartNum
        }
    })
    .OrderBy(x => x.Settings.VoucherStartNum)
    .ToList();

// This generates an error.
var errorProjection = _db.Customer
    .ProjectTo<CustomerDto>(mapperCfg)
    .OrderBy(x => x.Settings.VoucherStartNum)
    .ToList();

errorProjection引发错误:

System.InvalidOperationException: The LINQ expression 'OrderBy<Customer, int>(
    source: DbSet<Customer>, 
    keySelector: (c) => Property<Nullable<int>>(Property<CustomerSettings>(c, "Settings"), "CustomerId") == null ? null : new SettingsDto{ VoucherStartNum = Property<CustomerSettings>(c, "Settings").VoucherStartNum }
    .VoucherStartNum)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

这是为errorProjection

生成的表达式
EntityQueryable<Customer>.Select(
    dtoCustomer => new PaymentsController.CustomerDto
    {
        Name = dtoCustomer.Name,
        Settings = (dtoCustomer.Settings == null)
            ? null
            : new PaymentsController.SettingsDto
            {
                VoucherStartNum = dtoCustomer.Settings.VoucherStartNum
            }
    }).OrderBy(x => x.Settings.VoucherStartNum)

我猜这是由于AutoMappers ProjectTo函数包含的空检查所致。我该如何解决?

0 个答案:

没有答案