【问题标题】:Entity Framework not updating the foreign key实体框架不更新外键
【发布时间】:2019-12-16 22:15:46
【问题描述】:

我正在使用 ASP.NET Core 2.2 创建一个 Web API,我正在尝试使用 Put 方法更新对象。我创建了这个 DTO 对象:

    public class EditUserDTO 
    {
            [MaxLength(255)]
            public string Name { get; set; }
            [MaxLength(55)]
            public string MailAdress { get; set; }
            public Guid? ProfilId { get; set; }
    }

我的班级:

    public class User 
    {
            [MaxLength(255)]
            public string Name { get; set; }
            [MaxLength(55)]
            public string MailAdress { get; set; }
            [ForeignKey("ProfilId")]
            public Guid? ProfilId { get; set; }
            public virtual Profil Profil { get; set; }
    }

我的PUT 方法:

    public async Task<IActionResult> UpdateUser(Guid id, [FromBody]EditUserDTO user)
    {
        try
        {
            var userEntity = await _repoWrapper.UserRepo.GetUserByIdAsync(id);

            if (userEntity == null)
            {
                _logger.LogError($"User with id: {id}, hasn't been found in db.");
                return NotFound();
            }

            _mapper.Map(user, userEntity);              
            await _repoWrapper.UserRepo.UpdateUserAsync(userEntity);
            _repoWrapper.Save();

            return Ok();
        }
    }

我创建了一个自动映射器:

     public Mappers()
     {
         CreateMap<User, EditUserDTO>().ReverseMap();
     }

映射器执行后,外键ProfilIdDTO获取新值,但子对象Profil具有相同的旧值。

当我在执行PUT 后尝试从数据库中获取对象时,它仍然具有相同的旧值。

【问题讨论】:

标签: asp.net-core entity-framework-core asp.net-core-webapi


【解决方案1】:

看起来您正在使用新的个人资料 ID 更新您的实体,但您正在传回旧的个人资料。

您应该确定该个人资料是否存在。

你可以试试这样的:

    public async Task<IActionResult> UpdateUser(Guid id, [FromBody]EditUserDTO user)
    {
        try
        {
            var userEntity = await _repoWrapper.UserRepo.GetUserByIdAsync(id);
            var profileEntity = await _repoWrapper.ProfileRepo.GetProfileByIdAsync(user.ProfilId);

            if (userEntity == null)
            {
               _logger.LogError($"User with id: {id}, hasn't been found in db.");
               return NotFound();
            }

            if (profileEntity == null)
            {
               _logger.LogError($"Profile with id: {id}, hasn't been found in db.");
               return BadRequest();
            }

            _mapper.Map(user, userEntity);  

            userEntity.Profile = profileEntity;

            await _repoWrapper.UserRepo.UpdateUserAsync(userEntity);
            _repoWrapper.Save();

            return Ok();
        }
    }

【讨论】:

    猜你喜欢
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多