Asp.Net Core包含另一个FK的FK值

问题描述 投票:0回答:1

我在数据库中有3个模型,3个表(使用EF迁移创建):

public class Announce {
        public int Id { get; set; }
        public Location Location { get; set;}
        public int LocationId { get; set; }
}

public class Location {   
    public int Id { get; set; }
    public string Name { get; set; }
    public District District { get; set; }
    public string DistrictId { get; set; }
}

public class District {   
    public int Id { get; set; }
    public string Name { get; set; }
}

和Dto类:

public class AnnounceForListDto {
            public int Id { get; set; }            
            public string LocationName { get; set; }
            public string DistrictName{ get; set; }
    }

在AutoMapperProfile中:

CreateMap<District, AnnounceForListDto>()
                .ForMember(dest => dest.DistrictName, opt =>
                {
                    opt.MapFrom(dis => dis.Name);
                }); 

我想宣布:

public async Task<IEnumerable<Announce>> GetAnnounces()
        {
            var announces = await _context.Announce
                    .Include(prop => prop.Photos)
                    .Include(prop => prop.Location)
                    .ToListAsync();
            return announces;
        }

我需要在我的列表中包含区域名称(或区域ID,因为我使用AutoMapper来区分来自AnnounceForNameD的ZoneName与区域名称)。

我尝试了.Include(prop => prop.Location.District.Name),但得到一个错误,“Include只能使用一个”点“)。

也许.ThenInclude(Location => Location.District)这个帮助我错了我的Dto声明?

我的Dto用于控制器:

[HttpGet]
        public async Task<IActionResult> GetAnnounces()
        {
            var announces = await _repo.GetAnnounces();

            var announcesToReturn = _mapper.Map<IEnumerable<AnnounceForListDto>>(announces);

            return Ok(announcesToReturn);
        }
c# asp.net entity-framework asp.net-core include
1个回答
0
投票

解决:创建位置和区域之间的关系

那么,我的Repo方法:

var announces = await _context.Announce
                    .Include(prop => prop.Photos)
                    .Include(prop => prop.Location)
                        .ThenInclude(prop => prop.District)
                    .ToListAsync();
            return announces;
© www.soinside.com 2019 - 2024. All rights reserved.