Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...