使用Automapper来压缩属性的子类

时间:2010-05-17 04:50:05

标签: subclass automapper superclass

鉴于课程:

public class Person
{
    public string Name { get; set; }
}

public class Student : Person
{
    public int StudentId { get; set; }
}

public class Source
{
    public Person Person { get; set; }
}

public class Dest
{
    public string PersonName { get; set; }
    public int? PersonStudentId { get; set; }
}

我想使用Automapper来映射Source - > DEST。

这项测试显然失败了:

Mapper.CreateMap<Source, Dest>();
var source = new Source() { Person = new Student(){ Name = "J", StudentId = 5 }};

var dest = Mapper.Map<Source, Dest>(source);
Assert.AreEqual(5, dest.PersonStudentId);

如果“Person”实际上是整个域模型中使用频繁的数据类型,那么映射这个的最佳方法是什么。

编辑:目的是保留“Dest”对象,这些对象将为子类型“Person”的所有属性定义字段。因此,我们可以拥有如下所示的源对象,并且不希望为“Person”子类的每个可能组合创建Dest对象:

public class Source2
{
    public Person Value1 { get; set; }
    public Person Value2 { get; set; }
    public Person Value3 { get; set; }
    public Person Value4 { get; set; }
    public Person Value5 { get; set; }
}

1 个答案:

答案 0 :(得分:1)

使用Jimmy的建议我已经确定了以下解决方案:

public class Person
{
    public string Name { get; set; }
}

public class Student : Person
{
    public int StudentId { get; set; }
}
//all subtypes of person will map to this dto
public class PersonDto
{
    public string Name { get; set; }
    public int? StudentId { get; set; }
}

public class Source
{
    public Person Person { get; set; }
}

public class DestDto
{
    public PersonDto Person { get; set; }
}

public class Dest
{
    public string PersonName { get; set; }
    public int? PersonStudentId { get; set; }
}

[TestFixture]
public class RandomTests
{
    [Test]
    public void Test1()
    {
        Mapper.CreateMap<Person, PersonDto>();
        Mapper.CreateMap<Student, PersonDto>();

        Mapper.CreateMap<Source, DestDto>();
        Mapper.CreateMap<DestDto, Dest>();

        var source = new Source() { Person = new Student() { Name = "J", StudentId = 5 } };

        var destDto = Mapper.Map<Source, DestDto>(source);
        var destFinal = Mapper.Map<DestDto, Dest>(destDto);

        Assert.AreEqual(5, destFinal.PersonStudentId);
    }
}

很想听听建议/改进。