自动映射子实体未映射

时间:2018-02-23 19:34:21

标签: c# automapper

我试图映射包含默认子实体的父实体。

所以,我有一个promotion对象,它有一组localisedPromotion个对象

我想设置一个特定的localisedPromotion并将其设置为我的defaultLocalisedPromotion

在我的配置中,我有:

config.CreateMap<LocalisedPromotion, LocalisedPromotionViewModel>()
    .ForMember(dest => dest.LocalisedPromotionId, o => o.MapFrom(src => src.Id));

config.CreateMap<Promotion, PromotionViewModel>()
    .ForMember(dest => dest.DefaultLocalisedPromotion,
               o => o.MapFrom(src => src.LocalisedPromotions
                                        .FirstOrDefault(x => x.CultureId == src.DefaultCultureId)));

因此,我认为应该设置DefaultLocalisedPromotion

类型的字段LocalisedPromotionViewModel

但是该字段始终为空

是否有明显的方法来实现我想要实现的目标

1 个答案:

答案 0 :(得分:0)

我写了一个单元测试,似乎AutoMapper代码可以工作。请查看单元测试,并告诉我它是否正确或发布更多代码(尤其是您要映射的类),以便可以调整测试。

using AutoMapper;
using Xunit;

using System.Linq;
using System.Collections.Generic;

namespace AutoMapperTest
{
    public class LocalisedPromotion
    {
        public int Id;
        public int CultureId;
    }

    public class LocalisedPromotionViewModel
    {
        public int LocalisedPromotionId;
    }

    public class Promotion
    {
        public List<LocalisedPromotion> LocalisedPromotions;
        public int DefaultCultureId;
    }

    public class PromotionViewModel
    {
        public LocalisedPromotionViewModel DefaultLocalisedPromotion;
    }

    public class AutoMapperTest
    {
        [Fact]
        public void Test()
        {
            var theConfig = new MapperConfiguration(config =>
            {
                config.CreateMap<LocalisedPromotion, LocalisedPromotionViewModel>()
                    .ForMember(dest => dest.LocalisedPromotionId, o => o.MapFrom(src => src.Id));

                config.CreateMap<Promotion, PromotionViewModel>()
                    .ForMember(dest => dest.DefaultLocalisedPromotion,
                               o => o.MapFrom(src => src.LocalisedPromotions
                                                        .FirstOrDefault(x => x.CultureId == src.DefaultCultureId)));
            });

            var promotion = new Promotion { DefaultCultureId = 3 };
            promotion.LocalisedPromotions = new List<LocalisedPromotion>() { new LocalisedPromotion() { Id = 1, CultureId = 3 } };

            var result = theConfig.CreateMapper().Map<Promotion, PromotionViewModel>(promotion);

            Assert.NotNull(result.DefaultLocalisedPromotion);
            Assert.Equal(result.DefaultLocalisedPromotion.LocalisedPromotionId, 1);
        }
    }
}