【发布时间】:2020-09-19 21:58:34
【问题描述】:
假设我们有以下两个数据库表:
Foo:
> FooId (PK)
> FooName
Bar:
> BarId (PK, FK)
> Comment
> Other columns...
我有以下 EF 映射:
[Table("Foo")]
public class Foo
{
[Key]
public long FooId { get; set; }
public string FooName { get; set; }
// (0-n) relation
// public List<Bar> Bars { get; set; }
}
[Table("Bar")]
public class Bar
{
// PK/FK
[Key, ForeignKey("Foo")]
public long BarId { get; set; }
public string Comment { get; set; }
}
实体“Bar”只有一个外键作为主键。 每当我尝试像这样插入新的 Bar 实体时:
var demoList = new List<Bar>();
// Populate demoList with random data
_context.Bars.AddRange(demoList);
_context.SaveChanges();
我遇到了这个异常:
'The instance of entity type 'Bar' cannot be tracked because another instance with the same key value for {'BarId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'
EF 正在考虑“BarId”必须是唯一的,因为该属性被标记为“Key”,但它是一对多关系中的 PK/FK(“Foo”可以有 0 个或多个“Bar”),什么请问我这里不见了?
【问题讨论】:
-
如果您尝试使用您的 Foo 和 Bar 类型创建一个简短的、独立的复制品,您可能会自己解决。否则将其作为您问题的一部分发布。
标签: c# .net entity-framework asp.net-core entity-framework-core