EF Core Function 调用 Select 语句中的属性之一

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

我的查询中有这样的 MailingStatus 映射,它可以转换为 SQL

      var query = from m in _dbContext.Machine
                  select new MachineDto
                  {
                    MailingStatus = 
      m.EmailDistribution == EmailDistributionType.Daily ? MailingStatusType.One : 
      m.EmailDistribution == EmailDistributionType.Weekly ? MailingStatusType.Two : 
      MailingStatusType.Three
                  };
query = query.Where(x => x.MailingStatus == MailingStatusType.One);

但我想在单独的函数中进行 MailingStatus 映射,如下所示:

public class MachineUtils
{
  public static Func<MachineInfo, MailingStatusType> SetMailingStatus = (m) =>
    m.EmailDistribution == EmailDistributionType.Daily ? MailingStatusType.One : 
      m.EmailDistribution == EmailDistributionType.Weekly ? MailingStatusType.Two : 
      MailingStatusType.Three
}
...
var query = from m in _dbContext.Machine
                  select new MachineDto
                  {
                    MailingStatus = MachineUtils.SetMailingStatus(m)
                  };
query = query.Where(x => x.MailingStatus == MailingStatusType.One);

但在这种情况下,我收到错误:“无法翻译 LINQ 表达式。”

实现此类目标的正确方法是什么?

c# .net entity-framework linq
1个回答
0
投票

你的代码可以是这样的:

public class MachineUtils
    {
        public static Expression<Func<Machine, MachineDto>> SetMailingStatus = (m) =>
        new MachineDto
        {
            MailingStatus = m.EmailDistribution == EmailDistributionType.Daily ? MailingStatusType.One :
            m.EmailDistribution == EmailDistributionType.Weekly ? MailingStatusType.Two :
            MailingStatusType.Three
        };
    }

然后查询将像这样:

var query = _dbContext.Machine.Select(SetMailingStatus());
query = query.Where(x => x.MailingStatus == MailingStatusType.One);
© www.soinside.com 2019 - 2024. All rights reserved.