使用Db上下文的Include方法的问题 - Asp.Net Core

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

我在Asp.Net Core上有一个后台。数据库的结构是这样的。

  • User - 用户的基本信息:登录名,密码等。
  • Profile - 这个实体与 "User "是一对一的关系。
  • 个人档案照片--每个用户都有自己的照片集,这个实体与 "个人档案 "相连。

这里是 "用户 "实体。

    public class User
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Username { get; set; }
        public byte[] PasswordHash { get; set; }
        public byte[] PasswordSalt { get; set; }

        public Profile Profile { get; set; }
    }

然后是 "Profile":

    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; }
    }

还有 "ProfilePhotos":

    public class ProfilePhotos
    {
        public int Id { get; set; }
        public string ImageUrl { get; set; }

        public int ProfileId { get; set; }
        public Profile Profile { 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);
        }

为了得到所有的照片,我使用了 "profileService "的一个方法。

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

        }

在响应时,我想得到照片的id,photoUrl和用户名 所以我把我的个人资料照片映射到 "ProfilePhotosModel "上。

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

    }

但不幸的是,在回复中我只得到Id和photoUrl。用户名是空的 :(我到底做错了什么?

api asp.net-core asp.net-core-webapi backend web-deployment
1个回答
1
投票

你可以为 "用户 "添加自定义映射。Username 财产。

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<ProfilePhotos, ProfilePhotosModel>()
        .ForMember(m => m.Username, exp => exp.MapFrom(p => p.Profile.User.Username));
});
© www.soinside.com 2019 - 2024. All rights reserved.