繁体   English   中英

EF Core:无法跟踪实体类型的实例,因为另一个实例具有相同的键值

[英]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 ,则它是一对多关系。 如果关系是一对零或一,您通常会创建一个作为PrimaryKeyForiegnKey的键。 因此,根据您的要求,您的模型应该更像如下:

[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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM