Api 数据库上下文Asp.Net核心上使用Include方法的问题

Api 数据库上下文Asp.Net核心上使用Include方法的问题,api,asp.net-core,asp.net-core-webapi,backend,web-deployment,Api,Asp.net Core,Asp.net Core Webapi,Backend,Web Deployment,我在Asp.Net内核上有一个后端。数据库的结构如下所示: 用户-有关用户的基本信息:登录名、密码等 配置文件-此实体连接到“用户”一对一关系 个人资料照片-每个用户都有自己的照片集。 此实体已连接到“配置文件” 以下是“用户”实体: 然后配置文件: public class Profile { [ForeignKey("User")] public int Id { get; set; } public string B

我在Asp.Net内核上有一个后端。数据库的结构如下所示:

  • 用户-有关用户的基本信息:登录名、密码等
  • 配置文件-此实体连接到“用户”一对一关系
  • 个人资料照片-每个用户都有自己的照片集。 此实体已连接到“配置文件”
以下是“用户”实体:

然后配置文件:

    public class Profile
    {


        [ForeignKey("User")]
        public int Id { get; set; }

        public string BannerImageUrl { get; set; }
        public string ProfileImageUrl { get; set; }
        public string ShortDescription { get; set; }
        public string Description { get; set; }


        public User User { get; set; }
        public ICollection<ProfilePhotos> ProfilePhotos { get; set; }
    }
我想获取所有个人资料照片,因此我创建了一个端点:

        [HttpGet("{username}/photos")]
        public IActionResult GetPhotos(string username)
        {
            var profilePhotos = _profileService.GetAllPhotos(username);
            var model = _mapper.Map<IList<ProfilePhotosModel>>(profilePhotos);

            return Ok(model);
        }
但不幸的是,在回复中我只得到了Id和photoUrl。用户名为空:(
我做错了什么?

您可以为
用户名
属性添加自定义映射

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<ProfilePhotos, ProfilePhotosModel>()
        .ForMember(m => m.Username, exp => exp.MapFrom(p => p.Profile.User.Username));
});
var config=new-MapperConfiguration(cfg=>
{
cfg.CreateMap()
.ForMember(m=>m.Username,exp=>exp.MapFrom(p=>p.Profile.User.Username));
});

public ICollection ProfileImages{get;set;},ProfileImages类是否与ProfilePhotos相同,如果不相同,那么您可以共享ProfileImages代码吗?eh sry。我想更改为更好的匹配名称,但我没有找到。应该是“ProfilePhotos”,请提供您的映射代码。
        [HttpGet("{username}/photos")]
        public IActionResult GetPhotos(string username)
        {
            var profilePhotos = _profileService.GetAllPhotos(username);
            var model = _mapper.Map<IList<ProfilePhotosModel>>(profilePhotos);

            return Ok(model);
        }
        public IEnumerable<ProfilePhotos> GetAllPhotos(string username)
        {
            return _context.ProfilePhotos.Include(a=>a.Profile).ThenInclude(b=>b.User).Where(x => x.Profile.User.Username == username);

        }
    public class ProfilePhotosModel
    {
        public int Id { get; set; }
        public string ImageUrl { get; set; }
        public string Username { get; set; }

    }
var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<ProfilePhotos, ProfilePhotosModel>()
        .ForMember(m => m.Username, exp => exp.MapFrom(p => p.Profile.User.Username));
});