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

Map property to property of a collection 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: Only member accesses are allowed.

我该如何处理?

我澄清一下:视图模型和模型都有更多属性,问题类是示例

编辑:


我尝试了 Johnatan 提出的解决方案,它有效,这里的问题是我不能再进行单元测试了。

我正在用

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

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

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 } })); 

问题是您正在尝试映射到 .First()。 First 尚不存在,因为查询是在空/空集合上进行的。如果集合中的 .First() 元素尚不存在,则无法分配给该元素。而是直接映射为一个集合。

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 } }));