[英]EF Core (in-memory database) - 'The instance of entity type X cannot be tracked because another instance with the key value
[英]EF Core: The instance of entity type cannot be tracked because another instance with the same key value
假設我們有以下兩個數據庫表:
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
可以有 Zero 或 Many Bar
,則它是一對多關系。 如果關系是一對零或一,您通常會創建一個作為PrimaryKey
和ForiegnKey
的鍵。 因此,根據您的要求,您的模型應該更像如下:
[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.