【问题标题】:How to map DataTable to DTO by using automapper如何使用 automapper 将 DataTable 映射到 DTO
【发布时间】:2016-10-08 10:27:25
【问题描述】:

我是 AutoMapper 的新手,有几个关于数据表到对象映射的问题。我有 sqlquery 代码和 sql 结果。我想用自动映射器做对象到对象的映射。有什么帮助吗?

【问题讨论】:

    标签: c# datatable ado.net automapper


    【解决方案1】:

    我猜它可能会是这样的(粗线):

    AutoMapper.Mapper.CreateMap<DataSet, CompanyModel>()
         .ForMember(m => m.Company, opt => opt.MapFrom(r => r.Tables[0].Columns["Company"]))
         .ForMember(m => m.Customers, opt => opt.MapFrom(r => r.Tables[0].Columns["Customers"]))
         .ForMember(m => m.Amount, opt => opt.MapFrom(r => Double.Parse(r.Tables[0].Columns["Amount"]));
    

    然后

    Mapper.Map<List<CompanyModel>>(ds);
    

    提供更多细节(代码)可能会导致更准确的答案。

    【讨论】:

    • 我尝试了您的代码,但没有工作错误:AutoMapper.dll 中出现“AutoMapper.AutoMapperMappingException”类型的异常,但未在用户代码中处理。
    【解决方案2】:

    看这里Convert DataRow to Object with AutoMapper

    目前我是根据上面的方法做的,到目前为止,我只用原始类型的平面 DTO 进行了测试:

    public class CustomResolver : IValueResolver
    {
        public ResolutionResult Resolve(ResolutionResult source)
        {
            return source.New(Convert.ChangeType((source.Context.SourceValue as DataRow)[source.Context.MemberName], source.Context.DestinationType));
        }
    }
    
    
    public static class DtoTransformDataTable<T> where T : new()
    {
        public static IEnumerable<T> JustDoIt(DataTable dt)
        {
            Mapper.CreateMap<DataRow, T>().ForAllMembers(m => m.ResolveUsing<CustomResolver>());
            var listOfT = new List<T>();
    
            foreach (var item in dt.Rows) //Use LINQ to concise
            {
                var dest = Mapper.Map<T>(item);
                listOfT.Add(dest);
            }
            return listOfT;
        }
    }
    

    【讨论】:

    【解决方案3】:

    如果您使用普通的无类型 DataTables/DataSets,我认为 Automapper 不支持开箱即用。

    但是,如果您创建一个键入的 DataTable/DataSet,那么事情应该会更好。键入的DataSet 为每一列提供表格行属性,应该更容易与 AutoMapper 一起使用。

    我已经好几年没用过 DataSets 了,但是 .Net 仍然支持它们。 Look here 获取有关如何设置它们的一些信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 2018-03-19
      • 2014-10-21
      相关资源
      最近更新 更多