首页 > 解决方案 > 无法跟踪实体类型的实例,因为已在跟踪具有键值的另一个实例。但不是钥匙

问题描述

无法跟踪实体类型“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

标签: entity-framework

解决方案


推荐阅读