Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper - can it map over only existing properties in source and destination objects?

I have a simple update function:

public void Update(Users user)
{
    tblUserData userData = _context.tblUserDatas.Where(u => u.IDUSER == user.IDUSER).FirstOrDefault();
    if (userData != null)
    {
        Mapper.CreateMap<Users, tblUserData>();
        userData = Mapper.Map<Users, tblUserData>(user);
        _context.SaveChanges()
    }
}

userData is an EF entity, and it's Entity Key property gets nulled out because, I believe, it exists in the destination object, but not in the source object, so it gets mapped over with its default value (for the Entity Key, that's null)

So, my question is can Automapper be configured to only attempt to map the properties that exist in both the source and destination objects? I'd like things like the Entity Key and navigation properties to be skipped over.

like image 381
Mister Epic Avatar asked Jun 17 '13 12:06

Mister Epic


People also ask

Does AutoMapper map private properties?

By default, AutoMapper only recognizes public members. It can map to private setters, but will skip internal/private methods and properties if the entire property is private/internal.

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

Can AutoMapper map collections?

Polymorphic element types in collectionsAutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.

How does AutoMapper work in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.


1 Answers

You can explicitly tell AutoMapper to Ignore certain properties if required like this:

Mapper.CreateMap<Users, tblUserData>()
        .ForMember(dest => dest.Id, opt => opt.Ignore());

which will mean the Id column in the destination object will ALWAYS be left untouched.

You can use the Condition option to specify whether or not a mapping is applied depending on the result of a logical condition, like this:

Mapper.CreateMap<Users, tblUserData>()
        .ForMember(dest => dest.Id, opt => opt.Condition(src=>src.Id.HasValue));

or

Mapper.CreateMap<Users, tblUserData>()
        .ForMember(dest => dest.Id, opt => opt.Condition(src=>src.Id != null));

depending on your specific requirements.

like image 178
connectedsoftware Avatar answered Oct 04 '22 03:10

connectedsoftware