[英]Automapper child entities not mapping
Im trying to map a parent entity that includes a default child entity. 我正在尝试映射包括默认子实体的父实体。
So, I have a promotion
object, that has a collection of localisedPromotion
objects 因此,我有一个promotion
对象,其中包含localisedPromotion
对象的集合
I want to set a specific localisedPromotion
and set it as my defaultLocalisedPromotion
我想设置一个特定的localisedPromotion
并将其设置为我的defaultLocalisedPromotion
In my config I have: 在我的配置中,我有:
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)));
So in my mind this should set the field DefaultLocalisedPromotion
of type LocalisedPromotionViewModel
因此,在我看来,这应该将LocalisedPromotionViewModel
类型的字段DefaultLocalisedPromotion
设置为
However the field is always null 但是,该字段始终为空
Is there an obvious way of doing what I am trying to achieve 有什么明显的方法可以做我想达到的目标
I wrote a unit test and it seems that the AutoMapper code works. 我写了一个单元测试,看来AutoMapper代码可以工作了。 Please review the unit test and let me know if it is correct or post more code (especially the classes you want to map) so that the test can be adapted. 请检查单元测试,让我知道它是否正确,或者发布更多代码(尤其是要映射的类),以便可以更改测试。
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.