映射具有相同属性的2个类

时间:2017-09-01 10:03:17

标签: c# mapping

我在Class2中复制了具有相同属性但不是所有属性的Class1。在我的上下文中,我有一个用值初始化的Class1 obj(o1),我想用Class2 obj(o2)的值更改一些,而不会丢失o1数据(不在o2中的值)。手动,我需要重新指定o1的值为o2,所以我想找到一种自动方式来映射类。

课程:

public class Class1
{
    public bool Property1;
    public int Property2;
    public string Property3;
    public bool Property4;
    public int Property5;
    public string Property6;
    public bool Property7;
    public int Property8;
    public string Property9;
    public bool Property10;
    public int Property11;
    public string Property12;
    public bool Property13;
    public int Property14;
    public string Property15;
    public bool Property16;
    public int Property17;
    public string Property18;
    public bool Property19;
    public int Property20;
}

public class Class2
{
    public bool Property1;
    public int Property2;
    public string Property3;
    public bool Property7;
    public int Property8;
    public string Property9;
    public bool Property10;
    public int Property11;
    public string Property12;
    public bool Property13;
    public int Property14;
    public string Property15;
    public bool Property16;
    public int Property17;
    public string Property18;
    public bool Property19;
    public int Property20;

    public Class1 ToClass1()
    {
        return new Class1()
        {
            Property1 = Property1,
            Property2 = Property2,
            Property3 = Property3,
            Property7 = Property7,
            ...
            Property20 = Property20
        };
    }
}

如果我执行ToClass1(),则会丢失o1的Property4,Property5和Property6的值。

我现在做的事情:

// o1 and o2 are initialised with values.
o1.Property1 = o2.Property1;
o1.Property2 = o2.Property2;
o1.Property3 = o2.Property3;
o1.Property7 = o2.Property7;
...
o1.Property20 = o2.Property20;

1 个答案:

答案 0 :(得分:0)

您需要使用automapper并配置映射规则以忽略您不想映射的属性。

Look at this link