简体   繁体   中英

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:

[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. Whenever I try to insert new Bar entities like this:

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?

If Foo can have Zero or Many Bar s it is a One-To-Many relationship. You would typically create a key as both PrimaryKey and ForiegnKey if the relationship is One-to-Zero-or-One. 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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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