C#自动映射器将对象嵌套到平面对象列表 [英] c# automapper nested object to flat object list

查看:118
本文介绍了C#自动映射器将对象嵌套到平面对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下示例结构:

public class Client
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Adress> AdressList { get; set; }
}

public class Adress
{
     public Guid Id { get; set; }
     public string street { get; set; }
}

我想将此结构自动映射到 normalizr 对javascript所做的事情. 我想要一个看起来像这个对象的结果

I want to automap this structure to something what normalizr does for javascript. I want to have a result that looks like this object

public class ViewModelRoot
{
     public ICollection<ViewModelClient> ViewModelClientList { get; set; }
     public ICollection<ViewModelAdress> ViewModelAdressList { get; set; }
}
public class ViewModelClient
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<string> AdressIdList { get; set; }
}

public class ViewModelAdress
{
     public Guid Id { get; set; }
     public string street { get; set; }
}

映射应将我的Client类中的AdressList提取到同一级别的单独列表中,并应仅将其References替换为其Guid.

The mapping should extract the AdressList from my Client class to a seperate list on the same level and should replace the References with just its Guids.

我认为使用AutoMapper可以实现...任何想法? 提前非常感谢.

I think that could be possible with AutoMapper ... any ideas? Thanks a lot in advance.

推荐答案

Mapper.Initialize(cfg=>
{
    cfg.CreateMissingTypeMaps = false;
    cfg.CreateMap<Client, ViewModelRoot>()
        .ForMember(d=>d.ViewModelClientList, o=>o.MapFrom(s=>new[]{s}))
        .ForMember(d=>d.ViewModelAdressList, o=>o.MapFrom(s=>s.AdressList));
    cfg.CreateMap<Client, ViewModelClient>()
        .ForMember(d=>d.AdressIdList, o=>o.MapFrom(s=>s.AdressList.Select(a=>a.Id)));
    cfg.CreateMap<Adress, ViewModelAdress>();
});

这篇关于C#自动映射器将对象嵌套到平面对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆