如何使用 Automapper 将 List<Guid> 映射到 List<Class>?

问题描述 投票:0回答:2
public class A {
    public virtual ICollection<Person> People { get; set; } = new List<Person>();
}

public class B {
    public List<Guid> People { get; set; }
}

CreateMap<B, A>()
    .ForMember(dest => dest.People, opt => opt.MapFrom(src => ?));

错误 - AutoMapper.AutoMapperMappingException:缺少类型映射配置或不受支持的映射。

映射类型: 向导 -> 人

c# .net-core automapper
2个回答
0
投票

由于列表的数据类型是自定义类(

Person
),因此需要第二次映射配置。

CreateMap<B, A>()
    .ForMember(dest => dest.People, opt => opt.MapFrom(src => src.People));

CreateMap<Guid, Person>()
    . // Here define your map of how to create a Person object from Guid.

0
投票

您可以为

People
属性创建自定义映射。您需要迭代
Guid
值列表并使用相应的
Person
属性创建
Id
对象。这是一个例子:


public class Person
{
    public Guid Id { get; set; }
    // Other properties...
}

public class A
{
    public virtual ICollection<Person> People { get; set; } = new List<Person>();
}

public class B
{
    public List<Guid> People { get; set; }
}

//USE
var configuration = new MapperConfiguration(cfg =>
{
   cfg.CreateMap<B, A>().ForMember(dest => dest.People, opt => opt.MapFrom(src => src.People.Select(id => new Person { Id = id })));
});

IMapper mapper = configuration.CreateMapper();

var source = new B
{
    People = new List<Guid> { Guid.NewGuid(), Guid.NewGuid() }
};

A destination = mapper.Map<A>(source);

© www.soinside.com 2019 - 2024. All rights reserved.