将属性映射到集合自动映射器的属性

时间:2020-01-27 14:45:28

标签: c# automapper

我有两个实体

public class A{
    public string Example { get; set; }
    public ICollection<B> BCollection { get;set; } = new HashSet<B>();
}

public class B {
    public string MyProperty { get; set; }
}

还有一个简单的ViewModel

public class AFirstLoadViewModel {
    public string Example { get; set; }
    public string MyProperty { get; set; }
}

问题是,当A内只有一个B对象时,此视图模型将仅在第一个数据条目中使用。

所以,我正在尝试映射这样的对象:

var source = new AFirstLoadViewModel
{
    Example = "example",
    MyProperty = "myproperty"
}

对此

var destination = new A {
    Example = "example"
    BCollection = new List<B> {
        new B { MyProperty = "myproperty" }
    }
}

我尝试使用ForPathBeforeMap来达到目的,而没有运气

CreateMap<AFirstLoadViewModel, A>()
    .ForMember(x => x.Example, c => c.MapFrom(x => x.Example))
    .ForPath(x => x.BCollection.First().MyProperty, c => c.MapFrom(x => x.MyProperty))
    .BeforeMap((viewModel, entity) => {
        if(!entity.BCollection.Any())
            BCollection.Add(new B());
    });

但是我得到

System.ArgumentOutOfRangeException:仅允许成员访问。

我该如何处理?

我要澄清:视图模型和模型都具有更多的属性,问题类仅作为示例

编辑:


我尝试了Johnatan提出的解决方案,它的工作原理是,我不能再进行单元测试了。

我正在

var config = new MapperConfiguration(cfg => cfg.CreateMap<AFirstLoadViewModel, A>(MemberList.Source));

当我调用config.AssertConfigurationIsValid()失败时,因为MyProperty属性未映射

2 个答案:

答案 0 :(得分:2)

问题是您正在尝试映射到.First()。 First不存在,因为查询位于空/空集合上。如果集合中的.First()元素尚不存在,则不能将其分配。而是直接将其映射为集合。

var elmt = $('#myElmt');

elmt.on('click', myCallbackFunction);
elmt.on('hover', myCallbackFunction);

答案 1 :(得分:1)

CreateMap<AFirstLoadViewModel, A>()
    .ForMember(x => x.Example, c => c.MapFrom(x => x.Example))
    .ForMember(x => x.BCollection, c => c.MapFrom(x => new [] { new B { MyProperty = x.MyProperty } }));