简体   繁体   中英

Updating complex objects in database with AutoMapper - how to ignore nested objects for one time map?

Let me explain a bit. Here are my classes:

// ClassOne
int ID
string Name
ClassTwo ClassTwoExample

// ClassTwo
int ID
string Name
ClassThree ClassThreeExample
ClassFour ClassFourExample

// ClassThree
int ID
string Name

// ClassFour
int ID
string Name

So you get the general gist of it. ClassOne is my main / parent class and holds ClassTwo . ClassTwo holds a ton of information and references to even more classes. ClassThree and ClassFour are just reference classes which I do not need to modify.

My goal is to update the properties in ClassOne and the basic properties in ClassTwo ( ignoring ClassThree and ClassFour ). However, when I go to update using AutoMapper ( _mapper.Map(..,..) ), it's also trying to map ClassThree and ClassFour which end up being null and the database tries saving them.

Here is my mapping method:

// Mapping snippet
function (ClassOne model) {
    var oldClassOne = _repos.GetClassOne(model.ID);
    _mapper.Map(model, oldClassOne)
    await _repos.SaveAllAsync();
}

Is there anywhere in that piece of code where I can tell AutoMapper to ignore specific properties and just specifically map what I want it to?

Initialize your Mapper like this

public class AutoMapperConfig
{
    public static void RegisterMappings()
    {
        Mapper.Initialize(m =>
        {
            m.CreateMap<ClassOne, ClassOne>().ForMember(d => d.ClassTwoExample.ClassThreeExample, s => s.Ignore())
                                             .ForMember(d => d.ClassTwoExample.ClassFourExample, s => s.Ignore());
        });
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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