具有不同属性类型的AutoMapper对象

时间:2014-10-20 15:36:53

标签: c# entity-framework automapper

我想将我的Entity Framework实体(从遗留数据库生成)映射到自定义DTO对象(应该很好,干净)。

我的遗留数据库有实体看起来像这样:

internal class Order {
    int id;
    string Shipping_date;
    string quantity;
}

我想将它映射到更好的DTO对象:

public class OrderDto {
    int id;
    DateTime? ShippingDate;
    int Quantity;
}

我编写了一个“实体容器”来提供依赖注入,它以这种方式返回值:

public IEnumerable<OrderDto> GetPaginatedOrders(int page, int pageSize)
{
    return this.db.Orders
               .OrderByDescending(c => c.id)
               .Paginate(page, pageSize)
               .Project()
               .To<OrderDto>()
               .AsEnumerable();
}

所以:更改类型和更改属性名称。

只是改变了属性名称,这将是一件容易但又乏味的事情:

Mapper.CreateMap<Order, OrderDto>()
  .ForMember(dest => dest.Quantity, opt => opt.MapFrom(src => src.quantity))
  .ForMember(dest => dest.ShippingDate, opt => opt.MapFrom(src => src.Shipping_date));

这对于类型更改是不够的。我尝试了很多东西:

  • 在映射声明中解析属性,如src => int.Parse(src.quantity),但Linq不喜欢它。
  • 使用QuantityInt { get { return int.Parse(this.quantity) } }等自定义属性扩展EF实体并在映射中使用这些属性,但AutoMapper不喜欢它,并明确不支持它们。
  • 将系统类型彼此映射为Mapper.CreateMap<string, int>().ConvertUsing(Convert.ToInt32),但我仍然会遇到Unable to create a map expression from System.String to System.Int32错误。
  • 为我的班级使用自定义转换器,但我总是在运行时从我的实体中获取ResolutionContext.SourceValues的空值(我猜测它们是在AutoMapper获取它们之前处理它们或类似的东西)。

我意识到AutoMapper是基于会议的,所以也许我应该使用其他工具,但哪一个存在?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

.Project()使用Linq实体,它生成SQL并且自然只能理解一组非常有限的函数。

如果您使用

Mapper.Map<IEnumerable<Order>, IEnumerable<OrderDto>>(src) 

您的转化效果会很好。

相关问题