Reputation: 23
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?
Upvotes: 2
Views: 4751
Reputation: 2064
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; }
}
Upvotes: 1