【问题标题】:Automapper System.Exception "Can't resolve this to Queryable Expression"Automapper System.Exception“无法将其解析为可查询表达式”
【发布时间】:2015-01-04 13:30:16
【问题描述】:

我正在尝试在 automapper 中使用自定义值解析器来获取运行时两个日期之间的差异。

解析器

public class TotalDaysResolver : ValueResolver<JobPersonnel, double>
{
    protected override double ResolveCore(JobPersonnel source)
    {
        var totalDays = CalculateDaysBetween(source.LeaveOffice.GetValueOrDefault(), source.ReturnOffice.GetValueOrDefault());

        return totalDays;
    }

    private double CalculateDaysBetween(DateTime d1, DateTime d2)
    {
        if (d1 >= DateTime.Now || d1 == DateTime.MinValue) return 0;
        d2 = SetTimeNowIfDateOutIsMinValue(d2);

        var span = d2.Subtract(d1);
        var totalDays = span.TotalDays.ToString("F2");

        return Double.Parse(totalDays);
    }

    private DateTime SetTimeNowIfDateOutIsMinValue(DateTime d2)
    {
        if (d2 == DateTime.MinValue)
            d2 = DateTime.Now;
        return d2;
    }
}

视图模型

public class PersonnelVM
{
    public int Refno { get; set; }
    public int JobID { get; set; }}
    [UIHint("StartDate")]
    public DateTime? LeaveOffice { get; set; }
    [UIHint("EndDate")]
    public DateTime? ReturnOffice { get; set; }
    public double TotalDays { get; set; }
}

映射

CreateMap<PersonnelVM, JobPersonnel>()
            .ReverseMap()
            .ForMember(dst => dst.TotalDays, opt => opt.ResolveUsing<TotalDaysResolver>()));

查询

public IEnumerable<PersonnelVM> GetAllPersonnelByJobId(int jobid)
{
    return _dbRepository.GetWhere<PersonnelVM, JobPersonnel>(w => w.JobID == jobid); //This is where I get the error
}

如果我注释掉 TotalDays 的地图,映射不会引发任何错误。不幸的是,我在网上找不到任何信息来为我指明解决此问题的任何方向。我是编程新手,也是 automapper 新手。

有没有人了解这个错误和/或我可以如何自己调试这个问题?

【问题讨论】:

  • _dbRepository.GetWhere&lt;&gt; 在做什么?
  • 它使用投影来获取所有实体。我认为这就是问题所在:解析器在使用投影时无法正确映射。我已将解析器逻辑移到视图模型中,这正在工作。

标签: entity-framework automapper iqueryable


【解决方案1】:

ResolveUsing 不允许在针对 EF(实体)的投影操作中使用。您提到您将映射逻辑移动到视图模型中,但您也可以放弃自定义解析器并为您的 MapFrom 提供参数(尽管在您的特定情况下很复杂) - 请参阅 https://github.com/AutoMapper/AutoMapper/wiki/Queryable-Extensions

假设您的 TotalDays 属性...现在看起来像:

[IgnoreMap]
public double TotalDays => CalculateDaysBetween(this.LeaveOffice, this.ReturnOffice)

这类似于我有时对条件/计算属性采取的方法。我从数据库中填充“helper”属性,然后依靠 getter 来完成 Resolve。

不幸的是,这是我们目前能得到的最好结果(参见 https://github.com/AutoMapper/AutoMapper/issues/415),因为 AutoMapper 必须将表达式树交给 EF 查询引擎并丢失这些操作的上下文。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-09-22
  • 2016-01-21
  • 2021-09-16
  • 2012-07-22
  • 2020-01-01
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多