将两个源对象映射到三个对象

时间:2014-05-23 07:33:51

标签: c# automapper

我有两个源对象:

public class Book
{
    public int Id {get;set;}
    public IList<Unity> Unities {get;set;}
}

public class Unity
{
    public int Id {get;set;}
    public string Title {get;set;}
}

和三个目标对象:

public class DtoBook
{
    public int Id {get;set;}
    public DtoOrganization Organization {get;set;}
}

public class DtoOrganization
{
    public int Id {get;set;}
    public IList<DtoUnity> Unities {get;set;}
}

public class DtoUnity
{
    public int Id {get;set;}
    public string Title {get;set;}
}

我想将两个源对象Book和Unity映射到三个dto对象,但不存在组织源对象。如何使用Automapper进行操作?

感谢!!!

发布我的实际代码Automapper代码:

public static void Configure()
{
    Mapper.Reset();

    Mapper.CreateMap<Unity, Model.Organization>();

    Mapper.CreateMap<Book, Model.Manifest>()
            .ForMember(x => x.Version, y => y.UseValue("1.1"));                

    Mapper.AssertConfigurationIsValid();
}

public static Model.Manifest Map(Book book)
{
    Configure();
    Model.Manifest dtoManifest = Mapper.Map<Book, Model.Manifest>(book);
    return dtoManifest;
}

1 个答案:

答案 0 :(得分:0)

如果我没有遗漏任何内容,这可能会是这样的(如果您不想了解AutoMapper的工作方式,这是一种简单的方法):

class Program
{
    static void Main(string[] args)
    {
        var sampleBook = new Book { 
            Id = 1, 
            Unities = new List<Unity> { 
                new Unity { Id = 2, Title = "Title of unity" }, 
                new Unity { Id = 3, Title = "Title of unity" } 
            } 
        };

        var ourBookDto = new DtoBook
        {
            Id = sampleBook.Id,
            Organization = new DtoOrganization
            {
                Id = 666, // i don't know from where do you want to obtain this id
                Unities = sampleBook.Unities.Select(u => new DtoUnity { 
                    Id = u.Id,
                    Title = u.Title
                }).ToList()
            }
        };

        Console.ReadLine();
    }
}

但如果您的课程变得更加复杂,那么这可能会有点脏,所以请尝试使用AutoMapper