1

我想要一个通用更新方法,它复制 to 的所有属性,sourceObjecttargetObject不复制exceptions.

4

1 回答 1

0

你试过使用AutoMapper吗?它允许您定义自定义映射以及自动映射。

- 编辑 -

例子:

给定以下类型:

public class Type1
{
    public int MyProperty1 { get; set; }
    public int MyProperty2 { get; set; }
    public int MyProperty3 { get; set; }
    public int MyProperty4 { get; set; }
    public int MyProperty5 { get; set; }
}

public class Type2
{
    public int MyProperty1 { get; set; }
    public int MyProperty2 { get; set; }
    public int MyProperty3 { get; set; }
    public int MyProperty7 { get; set; }
    public int MyProperty8 { get; set; }
}

要创建忽略 2 个属性(MyProperty7 和 MyProperty8)的地图:

var map = Mapper.CreateMap<Type1, Type2>().
            ForMember(dest => dest.MyProperty7, opt => opt.Ignore()).
            ForMember(dest => dest.MyProperty8, opt => opt.Ignore());

最后复制:

Type2 type2Variable = Mapper.Map<Type1, Type2>(type1Variable);

--edit2--

映射相同类型示例:

var map = Mapper.CreateMap<Type1, Type1>().
            ForMember(dest => dest.MyProperty4, opt => opt.Ignore()).
            ForMember(dest => dest.MyProperty5, opt => opt.Ignore());

采用:

Type1 anotherType1Variable = Mapper.Map<Type1, Type1>(type1Variable);
于 2010-12-08T08:45:12.253 回答