我的查询中有这样的 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 表达式。”
实现此类目标的正确方法是什么?
你的代码可以是这样的:
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);