假设我们有以下两个数据库表:
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
可以有零个或许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; }
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句