使用自动映射器修剪对象属性期间的偶发错误

时间:2016-07-27 13:47:13

标签: c# asp.net-mvc asp.net-web-api automapper

public class Trimmer<TModel>
    {
       public Trimmer()
        {
            Mapper.Initialize(c =>
            {
                c.CreateMap<string, string>().ConvertUsing(s => string.IsNullOrEmpty(s) ? s : s.Trim());
                c.CreateMap<TModel, TModel>();
            });
        }

       /// <summary>
       /// Function take List of object of type TModel what supplied during initalization and applied trim on every property which is string.
       /// </summary>
       /// <param name="models">An model object of type TModel</param>
       /// <returns>List of objects of type TModel with string properties that are trimmed (leading and trailing spaces removed)</returns>
       public List<TModel> StringTrimmer(List<TModel> models)
       {
           if (models == null)
           {
               return null;               
           }
           var modelList = models.Select(StringTrimmer).ToList();
           return modelList;
       }

       /// <summary>
       /// Function take object of type T which one supply during Initalization and applied trim on every property which is string.
       /// </summary>
       /// <param name="model">An model object of Type TModel</param>
       /// <returns>Object of type TModel with string properties that are trimmed (leading and trailing spaces removed)</returns>
        public TModel StringTrimmer(TModel model)
        {
            Mapper.AssertConfigurationIsValid();`enter code here`
            var mappedObj = Mapper.Map<TModel,TModel>(model);
            return mappedObj;
        }

我使用称为StringTrimmer的重载方法创建了一个名为Trimmer的Generic类。方法的目的是使用Automapper修剪Tmodel对象属性的任何空间。它工作正常,但有时这些方法我得到以下错误:

  

找到未映射的成员。查看下面的类型和成员。添加一个   自定义映射表达式,忽略,添加自定义解析程序或修改   源/目的地类型。

当它不应该发生时,因为我将相同的对象类型转换为相同的对象类型。

1 个答案:

答案 0 :(得分:0)

Code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using AutoMapper;

namespace ConsoleApplication2
{
public class Data
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
public class DataDto
{
    public string FirstName { get; set; }
    public string No { get; set; }
}
public class ObjectModifier<TModel>
{
    public ObjectModifier()
    {
        Mapper.Initialize(c =>
        {
            c.CreateMap<string, string>().ConvertUsing(s => string.IsNullOrEmpty(s) ? s : s.Trim());
            c.CreateMap<TModel, TModel>();
            Mapper.AssertConfigurationIsValid();
        });
    }

    public TModel StringTrimmer(TModel model)
    {
        Mapper.AssertConfigurationIsValid();
        var mappedObj = Mapper.Map<TModel, TModel>(model);
        return mappedObj;
    }
}

public static class ObjectConverter
{
    public static T2 ToObject<T1, T2>(T1 val)
    {
        return Mapper.DynamicMap<T1, T2>(val);
    }
}

class Program
{ 
    static void Main(string[] args)
    {
        var doc = new Data()
        {
            FirstName = "Foo ",
            LastName = "ooF"
        };
        ObjectModifier<Data> objMod = new ObjectModifier<Data>();
        var result = objMod.StringTrimmer(doc);  //Good 
        var result2 = ObjectConverter.ToObject<Data, DataDto>(doc);  //Good
        var result3 = objMod.StringTrimmer(doc);   //Error
    }
}

}

@TimothyGhanem我发现问题是因为我使用的是Mapper.AssertConfigurationIsValid();在StringTrimmer的开头,它应该在Mapper.Initialize中的CreateMap之后。根据其偶尔的工作原因

  1. 案例 按照下面的代码。当main方法调用ObjectModifier类来修剪数据类属性时,Mapper.AssertConfigurationIsValid()将找到Data to Data的映射,这意味着Map的源和目标中的属性相同,从而得到通过验证。
  2. 案例 现在在下一行我们使用ObjectConverter中提到的新Map并将Data转换为Datadto工作正常。
  3. 案例 现在在下一行再次尝试使用StringTrimmer进行修剪,但现在当执行到Mapper.AssertConfigurationIsValid()时它将无效,因为Mapper保存来自ObjectConverter的前一个Map的上下文,现在Data和Datadto具有一些属性,实际上并不像数据中的“lastName”那样在Datadto中是“no”。因此失败。这是我提出的一个案例,它符合我寻求零星失败的一些解释。
  4. 由于