AutoMapper映射到可为空的属性的属性 [英] AutoMapper mapping to a property of a nullable property

查看:49
本文介绍了AutoMapper映射到可为空的属性的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将属性映射到可能为空的子属性?

How can you map a property to a sub-property that may be null?

例如,以下代码将因NullReferenceException而失败,因为联系人的User属性为null.

eg the following code will fail with a NullReferenceException because the Contact's User property is null.

using AutoMapper;

namespace AutoMapperTests
{
    class Program
    {
        static void Main( string[] args )
        {
            Mapper.CreateMap<Contact, ContactModel>()
                .ForMember( x => x.UserName,  opt => opt.MapFrom( y => y.User.UserName ) );

            Mapper.AssertConfigurationIsValid();

            var c = new Contact();

            var co = new ContactModel();

            Mapper.Map( c, co );
        }
    }

    public class User
    {
        public string UserName { get; set; }
    }

    public class Contact
    {
        public User User { get; set; }
    }

    public class ContactModel
    {
        public string UserName { get; set; }
    }
}

我希望ContactModel的UserName默认为空字符串.

I'd like ContactModel's UserName to default to an empty string instead.

我已经尝试过NullSubstititute方法,但是我认为这是在尝试使用User.Username进行操作,而不仅仅是在User属性上进行操作.

I have tried the NullSubstitute method, but I assume that's trying to operate with User.Username, rather than just on the User property.

推荐答案

您可以编写如下的映射代码:

You could write the mapping code like follows:

Mapper.CreateMap<Contact, ContactModel>()
            .ForMember( x => x.UserName,  opt => opt.MapFrom( y => (y.User != null) ? y.User.UserName : "" ) );

这将检查 User 是否为空,然后分配一个空字符串或 UserName .

This will check if the User is null or not and then assign either an emtpy string or the UserName.

这篇关于AutoMapper映射到可为空的属性的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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