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

标签 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;
}

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

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 不喜欢它。
  • 使用自定义属性扩展 EF 实体,例如 QuantityInt { get { return int.Parse(this.quantity) } }并在映射中使用它们,但 AutoMapper 不喜欢它,并且明确不支持它们。
  • 将系统类型从一个映射到另一个,例如 Mapper.CreateMap<string, int>().ConvertUsing(Convert.ToInt32)但我仍然得到 Unable to create a map expression from System.String to System.Int32错误。
  • 为我的类(class)使用自定义转换器,但我总是从 ResolutionContext.SourceValues 得到空值在运行时从我的实体(我猜测它们在 AutoMapper 获取它们或类似的东西之前被处置)。

我意识到 AutoMapper 是基于约定的,所以也许我应该使用另一种工具,但哪一种存在?

感谢您的帮助!

最佳答案

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

如果你使用

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

您的转换将正常进行。

关于c# - 具有不同属性类型的 AutoMapper 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26469525/

相关文章:

c# - 在 BeforeFeature 方法中初始化 webdriver

c# - 模拟测试方法

c# - Entity Framework 和 SCOPE_IDENTITY

odata - 如果 DTO 具有派生类,则使用 OData 选择的 Automapper 投影会抛出错误

c# - 无法加载我从未添加过的文件或程序集 'Microsoft.SharePoint.Library'

c# - 在 Linqpad 中获取 Entity Framework 上下文?

c# - ASP.NET MVC Image 使用 Entity Framework 在数据库上上传和创建记录

c# - 将远程 XML 文件导入 MVC 4 Webapp

c# - 如何将上下文值传递给 Automapper Map?

Automapper 集合