C# - 自动映射器不包括相关对象



我知道有很多关于自动映射器的问题。

我的问题是相关对象没有被自动映射器映射,但 foreignId 映射了。

 public class Location
 {
        public int Id { get; set; }
        public string Name{ get; set; }
        [ForeignKey("Company")]
        public int? CompanyId { get; set; }
        public Company Company { get; set; }
 }

Dto 对象:

 public class LocationDto
 {
        public int Id{ get; set; }
        public string Name{ get; set; }      
        public int? CompanyId { get; set; } // this is 1 - which the Company.Id
        public CompanyDto Company { get; set; } // this is NULL
 }

这里是映射配置:

var configurator= new MapperConfigurationExpression();
configurator.CreateMap<LocationDto, Location>()
    .ForMember(d => d.Company, opt => opt.MapFrom(s => s.Company));
configurator.CreateMap<Company, CompanyDto>();
configurator.CreateMap<CompanyDto, Company>();
Mapper.Initialize(configurator);

如果我很清楚,我以正确的方式做到了,因为我在很多帖子和教程中看到这个解决方案。

这里调用的映射命令:

Task.FromResult(Mapper.Map<TSource>(DataLayer.Get<TDest>(id)));

我不知道,为什么LocationDto.Company总是 NULL(但是LocationDto.CompanyId道具总是有价值(。你知道为什么这是空的吗?

我也尝试过没有ForMember,或者Member.Sourclist。

configurator.CreateMap<LocationDto, Location>();
configurator.CreateMap<LocationDto, Location>(Member.SourceList);

但没有任何帮助。

更新:公司

public class CompanyDto
    {
        public int Id{ get; set; }
        public string Title{ get; set; }
        public string Description { get; set; }
        public int? CountryId { get; set; }
        //public CountryDto Country { get; set; }
        public int? CountyId{ get; set; }
        //public County County{ get; set; }
        public bool Active { get; set; }
   }

这里是服务器部分:

 public class Company
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id{ get; set; }
        public string Title{ get; set; }
        public string Description { get; set; }
        [ForeignKey("Country")]
        public int? CountryId { get; set; }
        public Country Country { get; set; }
        [ForeignKey("County")]
        public int? CountyId{ get; set; }
        public County County{ get; set; }
        public bool Active { get; set; }
        public virtual ICollection<Haders> Haders { get; set; }
        public virtual ICollection<Parts> Parts{ get; set; }
        public Company()
        {
            this.Active = true;
        }
        public Company(string title, string description)
        {
            this.Title = title;
            this.Description = description;
        }
}
我想

,你忘记了这个:

configurator.CreateMap<CompanyDto, Company>()

您需要将 Comany -> CompanyDto 映射添加到配置中。

您必须使用Include加载方法与加载相关的对象,即它是预先加载。您可以使用 AutoMapper.EF6 来执行此操作。

context.Locations.Where(x => x.Id == 1)
                 .Include(l => l.Company)
                 .ProjectToFirst<LocationDto>(Mapper.Configuration);

最新更新