Automapper-是否可以仅映射源对象和目标对象中的现有属性? [英] Automapper - can it map over only existing properties in source and destination objects?

查看:201
本文介绍了Automapper-是否可以仅映射源对象和目标对象中的现有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的更新功能:

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是一个EF实体,它的Entity Key属性被清空了,因为我相信它存在于目标对象中,而不存在于源对象中,因此它被映射为其默认值(对于Entity Key ,那是空的)

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)

因此,我的问题是可以将Automapper配置为仅尝试映射源对象和目标对象中都存在的属性吗?我希望跳过实体键和导航属性之类的东西.

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.

推荐答案

如果需要,您可以明确地将AutoMapper告知Ignore某些属性:

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

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

这将始终使目标对象中的Id列保持不变.

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

您可以使用Condition选项来指定是否根据逻辑条件的结果来应用映射,例如:

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));

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

取决于您的特定要求.

这篇关于Automapper-是否可以仅映射源对象和目标对象中的现有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆