简体   繁体   English

如何将对象的属性 map 到对象的有序列表?

[英]How to map an object's properties to an ordered list of objects?

How can one map an object's properties to an ordered list of objects using automapper? map 如何使用自动映射器将对象的属性转换为有序的对象列表? The source type and it's properties are known at compile time.源类型及其属性在编译时是已知的。 The index at which each property should be in the destination must be resolved at runtime.每个属性应该在目标中的索引必须在运行时解析。 Validation that every source property is mapped is important.验证每个源属性都已映射很重要。

Consider this example of what I'm trying to achieve:考虑一下我想要实现的这个例子:

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Id { get; set; }
}

var configuration = new MapperConfiguration(cfg =>
{
    var map = cfg.CreateMap<Employee, List<object>>(MemberList.Source);
    //  some map configuration should go here.
    //  Preferrably one that maps a source property to an object in list at specified index.
}
configuration.AssertConfigurationIsValid();
var mapper = configuration.CreateMapper();
listOfProperties = mapper.Map(new Employee() { FirstName = "foo", LastName = "bar", Id = 0 });
// listOfProperties is a list of elements: { 0, "foo", "bar" };
// Order of elements in list should be a part of configuration

Can something like that be accomplished with automapper at all?可以用 automapper 完成类似的事情吗? If there is more than one suitable way to accomplish this, what are they?如果有不止一种合适的方法来实现这一点,它们是什么?

It is not very pretty but something like this will do:它不是很漂亮,但这样的事情会做:

var configuration = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Employee, List<object>>(MemberList.Source).ConvertUsing(
        (employee, _) => new List<object>()
        {
            employee.Id,
            employee.FirstName,
            employee.LastName
        });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM