我是 EF 的新手,正在努力做看似基本的更新。我已经阅读了许多关于类似问题的帖子。据我所知,目前这在 EF Core 2.1 中并不容易做到,需要复杂的解决方法。这实际上是可能的还是我应该直接和单独地更新子实体?
注意:如果我只是更新 exampleA 并且不包含子实体,它可以正常工作。
我收到以下错误:
处理请求时发生未处理的异常。InvalidOperationException:无法跟踪实体类型“ExampleB”的实例,因为已经在跟踪具有相同键值 {'Id'} 的另一个实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看冲突的键值。Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap.ThrowIdentityConflict(InternalEntityEntry 条目)
堆栈查询 Cookie 标头 InvalidOperationException:无法跟踪实体类型“ExampleB”的实例,因为已经在跟踪具有相同键值 {'Id'} 的另一个实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看冲突的键值。
我已经创建了这个问题的一个基本示例。第一个stackoverflow帖子也让我知道是否需要更多信息。
任何帮助将不胜感激。
WebAPI 控制器:
[HttpPut]
public async Task<ActionResult> UpdateExample(ExampleADto exampleADto)
{
var exampleAFromDB = await _context.ExampleA.Include(x => x.ExampleBs).Where(x => x.Id == exampleADto.Id).SingleOrDefaultAsync();
if (exampleAFromDB == null)
return NotFound();
_mapper.Map(exampleADto, exampleAFromDB);
if (await _context.SaveChangesAsync() > 0)
return Ok(exampleAFromDB);
throw new Exception("Failed to update ExampleA");
}
更新前数据库中的示例A:
{
"id": 1,
"description": "Example A1",
"exampleBDtos": [
{
"id": 1,
"description": "B1",
"someNumber": 1
},
{
"id": 2,
"description": "B2",
"someNumber": 2
},
{
"id": 3,
"description": "B3",
"someNumber": 3
}
]
}
示例ADto:
{
"id": 1,
"description": "Example A1 Updated",
"exampleBDtos": [
{
"id": 1,
"description": "B1 Updated",
"someNumber": 1
},
{
"id": 2,
"description": "B2",
"someNumber": 2
},
{
"id": 3,
"description": "B3",
"someNumber": 3
}
]
}
自动映射后的示例A:
{
"id": 1,
"description": "Example A1 Updated",
"exampleBDtos": [
{
"id": 1,
"description": "B1 Updated",
"someNumber": 1
},
{
"id": 2,
"description": "B2",
"someNumber": 2
},
{
"id": 3,
"description": "B3",
"someNumber": 3
}
]
}
更新失败后数据库中的示例A(无更改):
{
"id": 1,
"description": "Example A1",
"exampleBDtos": [
{
"id": 1,
"description": "B1",
"someNumber": 1
},
{
"id": 2,
"description": "B2",
"someNumber": 2
},
{
"id": 3,
"description": "B3",
"someNumber": 3
}
]
}
AutoMapper 配置文件:
public AutoMapperProfiles()
{
CreateMap<ExampleA, ExampleADto>()
.ForMember(x => x.ExampleBDtos, opt => opt.MapFrom(x => x.ExampleBs));
CreateMap<ExampleB, ExampleBDto>();
CreateMap<ExampleADto, ExampleA>()
.ForMember(x => x.ExampleBs, opt => opt.MapFrom(x => x.ExampleBDtos));
CreateMap<ExampleBDto, ExampleB>();
}
更新 1: 自动映射后添加对象
更新 2: 似乎 Automapper 不会在不删除和重新创建与 EF 混淆的项目的情况下映射集合。
AutoMapper.Collection https://www.nuget.org/packages/AutoMapper.Collection/目前不适用于 EF Core,所以我自己创建了一个函数来手动映射和更新集合。