【问题标题】:AutoMapper > Using Queryable Extensions and some mapping failsAutoMapper > 使用可查询扩展和一些映射失败
【发布时间】:2021-05-31 10:55:35
【问题描述】:

有没有办法用 AutoMapper 映射这些EntityFramework 实体?

我在尝试将 DateTime 对象(来自我的 DBContext 实体)映射到我的 DTO 上的 TimeSpan 属性时遇到错误。

这是个例外

----------- Exception #0 -----------
Type: System.NotSupportedException
Message: The specified type member 'TimeOfDay' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
Source: EntityFramework

它曾经在ToList()调用后映射实体时工作,但现在使用AutoMapper的ProjectTo<> IQueryable扩展,它显然试图将表达式转换为SQL可以理解的表达式。

我的问题 - 是否可以在服务器上执行查询后配置某些对象上的映射? (例如在ToList() 通话之后)

DB 实体上的 CloseTime 属性是 DateTime 对象,但我们正在映射到 TimeSpan 对象

现在 - 我只是忽略了这样的属性

cfg.CreateMap<CustomerShipTo, ShipToBase>()
    .ForMember(desc => desc.OpenTime, src => src.Ignore())
    //.ForMember(desc => desc.OpenTime, src => src.CloseTime.TimeOfDay)
    .ReverseMap();

【问题讨论】:

  • 你遇到了什么错误?
  • 您能否分享模型、您在哪里使用ProjectTo 的查询以及您现在收到的错误消息。这真的会帮助其他人了解您的问题。
  • 请注意这里可能的 X/Y 情况:My question - is it possible to configure mapping on certain objects to take place after the query has been executed on the server? (e.g. after the ToList() call) 真正的问题是:“尝试将 DateTime 对象(从我的 DBContext 实体)映射到 TimeSpan 时出现错误我的 DTO 上的财产。”
  • 添加了异常细节...

标签: c# entity-framework automapper iqueryable


【解决方案1】:

.ProjectTo() 需要能够最终映射到 SQL,因此与使用 .Map() 相比,映射可以执行的操作存在限制。解决此类问题的方法是映射“原始”数据值,然后在 DTO 中使用转换属性。在您的情况下,由于这是一种数据类型转换,您可以调用原始值“OpenDateTime”,通常如果我想使用相同的名称,我将使用前缀“Raw”来反映原始 DB 值。 (即 RawOpenTime)

[Serializable]
public class ShipToBase
{
    // ...
    public DateTime OpenDateTime { get; set; }
    public Timespan OpenTime
    {
        get { OpenDateTime.TimeOfDay; }
        set { OpenDateTime = DateTime.MinValue().Add(value); } // Setter if needed.
    }
}

然后在映射中:

cfg.CreateMap<CustomerShipTo, ShipToBase>()
    .ForMember(desc => desc.OpenDateTime, src => src.OpenTime)
    .ForMember(desc => desc.OpenTime, src => src.Ignore())
    .ReverseMap();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-20
    • 2013-12-14
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    相关资源
    最近更新 更多