多个来源和条件

时间:2017-10-24 18:28:23

标签: c# automapper

我正在努力弄清楚AutoMapper在将多个来源映射到一个目的地时的工作方式,并且必须相互比较这些来源。

来源

public class ProductSource
{
        public string Name { get; set; }
        public Category Category { get; set; }
        public List<AttributeValue> AttributeValues { get; set; }
}

public class Category
{
        public string Name { get; set; }
        public List<AttributeKey> AttributeKeys { get; set; }
}

public class AttributeKey
{
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Category> Categorys { get; set; }
}

public class AttributeValue
{
        public int Id { get; set; }
        public string Value { get; set; }
        public AttributeKey AttributeKey { get; set; }
}

Json中源代码的输出示例:

"Product": {
    "Name": "Nikon D70s",
    "Category": {
        "Name": "Camera",
        "AttributeKeys": {
            { "Id": 1001, "Name": "Resolution" },
            { "Id": 1002, "Name": "Size" },
            { "Id": 1003, "Name": "Color" }

        }
    },
    "AttributeValues" {
        { "id": 10001, "Value": "6 megapixel", "AttributeKey": 1001 },
        { "id": 10002, "Value": "Black", "AttributeKey": 1003 }
    }
}

目标

public class ProductDestination
{
        public string Name { get; set; }
        public string CategoryName { get; set; }
        public List<Attribute> Attributes { get; set; }
}

public class Attribute
{
        public string Name { get; set; }
        public string Value { get; set; }
}

我想要的输出示例,在Json中:

"Product": {
    "Name": "Nikon D70s",
    "CategoryName": "Camera",
    "Attributes": {
        { "Name": "Resolution ", "Value": "6 megapixel" },
        { "Name": "Size", "Value": "" },
        { "Name": "Color", "Value": "Blue" }
    }
}

我希望这很容易

我希望能够轻松实现自动化#34;映射发生。

CreateMap<ProductSource, ProductDestination>()
    .ForMember(d => d.Name, o => o.MapFrom(s => s.Name))
    .ForMember(d => d.CategoryName, o => o.MapFrom(s => s.Category.Name))
    .ForMember(d => d.Attributes, o => o.MapFrom(s => s.Category.AttributeKeyCategory.AttributeKeys));

CreateMap<AttributeKeys, Attribute>()
    .ForMember(d => d.Name, o => o.MapFrom(s => s.Name));

CreateMap<AttributeValue, Attribute>()
    .ForMember(d => d.Value, o => o.MapFrom(s => s.Value));

如何获取两个来源,将它们相互比较并将它们合并到一个目的地?

编辑:当我将AttributKey映射到属性时,我需要返回到grand-grand-parents其他子节点(AttributeValue)并遍历所有AttributeValues,如果有一个AttributeKeyId值与我的Id匹配的实例AttributeKey然后将此值映射到我的属性...

0 个答案:

没有答案