首页 > 解决方案 > 使用 AutoMapper 将 ef 模型映射到 dto,DateTime 数据类型引发异常

问题描述

我正在制作 Web Api + Entity Framework 应用程序。所以我正在使用AutoMapper将 EF 模型类映射到 DTO 类。

这是AutoMapper重要的配置之一Apartment。此方法在Global.asx文件中调用

public class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(cfg => 
        {
            cfg.CreateMap<Amenities, AmenitiesDTO>();
            cfg.CreateMap<Image, ImageDTO>();
            cfg.CreateMap<Location, LocationDTO>();
            cfg.CreateMap<Comment, CommentDTO>();
            cfg.CreateMap<Reservation, ReservationDTO>();
            cfg.CreateMap<Apartment, ApartmentDTO>();
        });
    }
}

这是ApartmentDTO课堂上有问题的属性。

public List<DateTime> FreeDate { get; set; }

这是Apartment课堂上有问题的属性。

[Column(TypeName = "datetime2")]
public List<DateTime> FreeDate { get => freeDate; set => freeDate = value; }        

这是我使用 Postman 定位的控制器操作。

public IQueryable<ApartmentDTO> GetApartments()
{
    var apartments = db.Apartments
        .Include(a => a.Amenities)
        .Include(a => a.Images)
        .Include(a => a.Location)
        .Include(a => a.Reservations.Select(c => c.Comment)).ProjectTo<ApartmentDTO>();


    return apartments;
}

我收到以下错误:

The specified type member 'FreeDate' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

所以我需要对DateTime数据类型做一些事情,以便它可以与 DTO 一起使用并在 Postman 中获得工作响应。什么?

编辑:我猜这个问题与 in 有关List<DateTime>,因为我有完全相同的设置DateTimeinReservationsController并且它工作正常。

标签: c#entity-frameworkasp.net-web-apiautomapper

解决方案


推荐阅读