简体   繁体   English

如何告诉 AutoMapper 使用“通过引用传递”?

[英]How to tell AutoMapper to use "pass by reference?"

By default automapper creates a new object based on the destination's type:默认情况下,自动映射器根据目的地的类型创建一个新对象:

public void Doit( Person personMissingStuff )
{
    PersonTemplate template = _personDao.GetPersonTemplate(1);
    Mapper.CreateMap<PersonTemplate, Person>();
    Person basePerson = Mapper.Map<Person>( template );
    Mapper.CreateMap<Person, Person>();
    Person completePerson = 
       Mapper.Map<Person, Person>( basePerson, personMissingStuff );
    ...
}

Instead of getting a completePerson I just get a basePerson again.而不是得到一个completePerson我只是再次得到一个basePerson How do I tell AutoMapper to run the mappings by reference instead of by value?如何告诉 AutoMapper 按引用而不是按值运行映射?

Mapper.Map(source, dest) actually returns the destination object, in your case it'll be personMissingStuff . Mapper.Map(source, dest)实际上返回目标对象,在您的情况下它将是personMissingStuff

With that said, assuming that you want to fill in only the null properties in the destination, you need to configure the mapping properly, and not map when the destination property has value.话虽如此,假设您只想填充目标中的空属性,则需要正确配置映射,并且在目标属性有值时不映射。

The following sample does exactly this for class properties.以下示例正是针对类属性执行此操作的。 For value properties, probably you need to do additional configuration.对于值属性,您可能需要进行额外的配置。 The example uses NUnit and SharpTestsEx:该示例使用 NUnit 和 SharpTestsEx:

[TestFixture]
public class LoadIntoInstance
{
    public class Template
    {
        public string Name { get; set; }
    }

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

    [Test]
    public void Should_load_into_instance()
    {
        Mapper.CreateMap<Template, Person>()
            .ForMember(d=>d.OtherData, opt=>opt.Ignore());
        Mapper.CreateMap<Person, Person>()
            .ForAllMembers(opt=>opt.Condition(ctx=>ctx.DestinationValue==null));
        Mapper.AssertConfigurationIsValid();

        var template = new Template {Name = "template"};
        var basePerson = Mapper.Map<Person>(template);

        var noNamePerson = new Person {OtherData = "other"};

        var result = Mapper.Map(basePerson, noNamePerson);

        result.Should().Be.SameInstanceAs(noNamePerson);
        result.Satisfy(r =>
                       r.Name == "template" &&
                       r.OtherData == "other");
    }
}

Just use traditional shallow cloning...只需使用传统的浅克隆...

Person completePerson = basePerson.MemberwiseClone();

This should keep the reference types and clone the value types.这应该保留引用类型并克隆值类型。

MSDN Link MSDN链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM