entity-framework - 无法跟踪实体类型的实例,因为已在跟踪具有键值的另一个实例。但不是钥匙
问题描述
无法跟踪实体类型“Cottage”的实例,因为已在跟踪另一个具有键值“{CottageCode: 7777}”的实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。
我正在使用 EF 内存数据库进行测试。
鉴于此配置
builder.ToTable("Cottage");
builder.HasKey(x => x.CottageId);
builder.Property(x => x.CottageId).IsRequired();
builder.Property(x => x.CottageCode);
我不明白为什么 EF 认为 CottageCode 是关键!
错误发生在 WebApplicationFactory 中的数据库填充期间
var cottage20207777 = new Cottage
{
CottageId = 20207777,
CottageCode = 7777,
Name = "Cottage 20207777",
};
var cottage20217777 = new Cottage
{
CottageId = 20217777,
CottageCode = 7777,
Name = "Cottage 20217777",
};
context.Cottages.Add(cottage20203728);
context.Cottages.Add(cottage20203810);
context.Cottages.Add(cottage20207777);
context.Cottages.Add(cottage20217777); // boom! exception
解决方案
推荐阅读
- powershell - Set-ExecutionPolicy RemoteSigned 禁用自动完成功能
- python - 熊猫数据框的 groupby 给出了错误的结果
- sql - 递归 CTE 表 - 计算 EWMA (EMA) - 如何优化/重构此代码,使其不会每次都被 TDWM 杀死?
- python-3.x - 配置 Gmail 帐户以向主题发送邮箱更新通知
- python - Sagemaker CPU 性能缓慢
- python - 使用自定义训练循环进行训练期间的 NaN 损失和 NaN 输出
- vbscript - 在 VBScript 中,如何检索 InstancesOf 集合的第一个元素?
- filter - PowerBI DAX Rank 基础过滤度量
- python - 使用 Pip 下载在 pyproject.toml 中声明的依赖项
- python - python - 如何在python的for循环中将项目附加到列表中?