Asp.net core 实体框架未更新外键

Asp.net core 实体框架未更新外键,asp.net-core,entity-framework-core,asp.net-core-webapi,Asp.net Core,Entity Framework Core,Asp.net Core Webapi,我正在使用ASP.NET Core 2.2创建一个Web API,我正在尝试使用Put方法更新对象。我创建了此DTO对象: 公共类EditUserDTO { [最大长度(255)] 公共字符串名称{get;set;} [MaxLength(55)] 公共字符串MailAddress{get;set;} 公共Guid?ProfilId{get;set;} } 我的班级: 公共类用户 { [最大长度(255)] 公共字符串名称{get;set;} [MaxLength(55)] 公共字符串Mail

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

公共类EditUserDTO
{
[最大长度(255)]
公共字符串名称{get;set;}
[MaxLength(55)]
公共字符串MailAddress{get;set;}
公共Guid?ProfilId{get;set;}
}
我的班级:

公共类用户
{
[最大长度(255)]
公共字符串名称{get;set;}
[MaxLength(55)]
公共字符串MailAddress{get;set;}
[外键(“ProfilId”)]
公共Guid?ProfilId{get;set;}
公共虚拟Profil Profil{get;set;}
}
我的
PUT
方法:

public async Task UpdateUser(Guid id,[FromBody]EditUserDTO用户)
{
尝试
{
var userEntity=await _repoWrapper.UserRepo.GetUserByIdAsync(id);
if(userEntity==null)
{
_logger.LogError($“在数据库中找不到id为:{id}的用户。”);
返回NotFound();
}
_mapper.Map(用户、用户实体);
wait_repoWrapper.UserRepo.UpdateUserAsync(userEntity);
_repoWrapper.Save();
返回Ok();
}
}
我创建了一个自动映射器:

publicmappers()
{
CreateMap().ReverseMap();
}
执行映射程序后,外键
Profil
DTO
获取新值,但子对象
Profil
具有相同的旧值


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

看起来您正在使用新的配置文件id更新实体,但也在传回旧的配置文件

您应该确保该配置文件是否存在

您可以尝试以下方法:

public async Task UpdateUser(Guid id,[FromBody]EditUserDTO用户)
{
尝试
{
var userEntity=await _repoWrapper.UserRepo.GetUserByIdAsync(id);
var profileEntity=wait _repoWrapper.ProfileRepo.GetProfileByIdAsync(user.ProfilId);
if(userEntity==null)
{
_logger.LogError($“在数据库中找不到id为:{id}的用户。”);
返回NotFound();
}
if(profileEntity==null)
{
_logger.LogError($”id为:{id}的配置文件,在db中未找到。“);
返回请求();
}
_mapper.Map(用户、用户实体);
userEntity.Profile=profileEntity;
wait_repoWrapper.UserRepo.UpdateUserAsync(userEntity);
_repoWrapper.Save();
返回Ok();
}
}