[英]EF Core: The instance of entity type cannot be tracked because another instance with the same key value
Assume we have the two following database tables:假设我们有以下两个数据库表:
Foo:
> FooId (PK)
> FooName
Bar:
> BarId (PK, FK)
> Comment
> Other columns...
I have the following EF mapping:我有以下 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; }
}
The entity "Bar" has only a foreign key as primary key.实体“Bar”只有一个外键作为主键。 Whenever I try to insert new Bar entities like this:
每当我尝试像这样插入新的 Bar 实体时:
var demoList = new List<Bar>();
// Populate demoList with random data
_context.Bars.AddRange(demoList);
_context.SaveChanges();
I'm getting this exception:我得到了这个例外:
'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 is considering that "BarId" must be unique as the property is marked as "Key", but it's a PK/FK in a one to many relation ("Foo" can have 0 or many "Bar"), what I'm missing here please? EF 正在考虑“BarId”必须是唯一的,因为该属性被标记为“Key”,但它是一对多关系中的 PK/FK(“Foo”可以有 0 个或多个“Bar”),我是什么请问这里不见了?
If Foo
can have Zero or Many Bar
s it is a One-To-Many relationship.如果
Foo
可以有 Zero 或 Many Bar
,则它是一对多关系。 You would typically create a key as both PrimaryKey
and ForiegnKey
if the relationship is One-to-Zero-or-One.如果关系是一对零或一,您通常会创建一个作为
PrimaryKey
和ForiegnKey
的键。 So per your requirement you models should be more like below:因此,根据您的要求,您的模型应该更像如下:
[Table("Foo")]
public class Foo
{
[Key]
public long FooId { get; set; }
public string FooName { get; set; }
public virtual List<Bar> Bars { get; set; }
}
[Table("Bar")]
public class Bar
{
[Key]
public long BarId { get; set; }
public long FooId { get; set; }
[ForeignKey("FooId")]
public virtual Foo Foo { get; set; }
public string Comment { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.