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.
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.
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.
Polymorphic element types in collectionsAutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With