我有两张桌子
create table AAA ( AAAKey int primary key, .... )
create table BBB (
AAAKey int references AAA(AAAKey), -- Foreign key to AAA
X int references X (XKey),
....
primary key (AAA, X))
在C#中,由EF 6.1.3生成的类
[Table("dbo.AAA")]
public partial class AAA
{
public AAA() { BBB = new HashSet<BBB>(); }
[Key] public int AAAKey { get; set; }
public virtual ICollection<BBB> BBB { get; set; }
}
[Table("dbo.BBB")]
public partial class BBB
{
[Key] public int AAAKey { get; set; }
[Key] public int XKey { get; set; }
public virtual AAA AAA { get; set; }
}
......
protected override void OnModelCreating(DbModelBuilder medelBuilder)
{
....
modelBuilder.Entity<AAA>()
.HasMany(e => e.BBB)
.WithRequired(e => e.AAA)
.HasForeignKey(e => e.AAAKey)
.WillCascadeOnDelete(false);
但是,代码在运行SaveChanges()
?
更新
问题很奇怪,它只发生在一些数据上。我通过将原始foreach (...) {...}; SaveChange()
转换为foreach (.....) { .....; SaveChange(); }
来找到解决方案。听起来像EF的错误吗?顺便说一句,我测试的所有数据总是有重复的密钥插入异常,这是预期的。
答案 0 :(得分:0)
你的意思是AAAKey
是外键吗?
public partial class BBB
{
[ForeignKey("AAA")]
public int AAAKey { get; set; }
public virtual AAA AAA { get; set; }
// other stuff...
}