为什么我无法使Automapper参数化工作

时间:2018-08-08 07:52:04

标签: c# automapper

给出以下自动映射器配置文件:

 public class MyProfile: Profile
 {
   private int? _injectedInt;

    public MyProfile()
    {

      CreateMap<objectA, objectB>()
     .ForMember(e => e.myNullableInt, x => x.MapFrom(s =>_injectedInt.HasValue ? 100 : 0));


    }
  }

以及以下代码:

var result = queryableOfObjectA.ProjectTo<objectB>(new { _injectedInt = 1 });

var resultingValue = result.FirstOrDefault().myNullableInt;

为什么“ resultingValue”返回0而不是100?

我看不到文档做错了什么

http://docs.automapper.org/en/stable/Queryable-Extensions.html#parameterization

1 个答案:

答案 0 :(得分:1)

我认为声明_injectedInt的地方可能是问题所在。我已经编写了以下测试,并且返回了100。

[TestClass]
public class UnitTest19
{
    [TestMethod]
    public void TestMethod1()
    {
        Mapper.Initialize(expression => expression.AddProfile(new MyProfile()));

        var queryableOfObjectA = new List<objectA>
        {
            new objectA
            {
                myNullableInt = 10
            }
        };

        var result = queryableOfObjectA.AsQueryable().ProjectTo<objectB>(new { _injectedInt = (int?)1 });

        var resultingValue = result.FirstOrDefault()?.myNullableInt;

        Assert.AreEqual(100, resultingValue);
    }
}

public class MyProfile : Profile
{
    public MyProfile()
    {
        int? _injectedInt = null;

        CreateMap<objectA, objectB>()
            .ForMember(e => e.myNullableInt, x => x.MapFrom(s => _injectedInt.HasValue ? 100 : 0));
    }
}

public class objectA
{
    public int myNullableInt { get; set; }
}

public class objectB
{
    public int myNullableInt { get; set; }
}