为什么EF代码优先生成多余的外键列? [英] Why is EF code-first generating an extraneous foreign key column?
问题描述
我使用实体框架代码优先自动创建我的数据库架构,我的实体之一是这样的:
I'm using entity framework code-first to create my database schema automatically, and one of my entities looks like this:
public class AssessmentsCaseStudies {
#region Persisted fields
[Required]
[Key, Column(Order=0)]
[ForeignKey("Assessment")]
public int AssessmentId { get; set; }
[Required]
[Key, Column(Order=1)]
[ForeignKey("CaseStudy")]
public int CaseStudyId { get; set; }
[Required]
public int Score { get; set; }
[ForeignKey("Follows")]
public int? FollowsCaseStudyId { get; set; }
#endregion
#region Navigation properties
public virtual Assessment Assessment { get; set; }
public virtual CaseStudy CaseStudy { get; set; }
public virtual CaseStudy Follows { get; set; }
#endregion
}
当EF自动生成我的数据库,它生成一个表具有以下的列:
When EF auto-generates my database, it generates a table with the following columns:
AssessmentId (PK, FK, int, not null)
CaseStudyId (PK, FK, int, not null)
Score (int, not null)
FollowsCaseStudyId (FK, int, null)
CaseStudy_CaseStudyId (FK, int, null)
这是所有罚款从 CaseStudy_CaseStudyId
列分开。为什么说已经产生?这是什么呢?我怎样才能阻止正在生成的呢?我怀疑是EF可以不再自动匹配的案例研究
的ICollection< AssessmentsCaseStudies>
与 CaseStudyId
列,因此它会创建自己列两个为导航属性链接在一起。
This is all fine apart from the CaseStudy_CaseStudyId
column. Why has that been generated? What is it for? How can I stop it being generated? My suspicion is that EF can no longer automatically match up CaseStudy
's ICollection<AssessmentsCaseStudies>
with the CaseStudyId
column, so it creates its own column to link the two together for that navigation property.
推荐答案
由于某些原因,Slauma的 InverseProperty
属性的建议没有工作。是什么做的工作是我指定的 AssessmentsCaseStudies
两个案例研究
导航性能之间的关系,以及案例研究
实体,通过在我的数据库上下文的 OnModelCreating
方法流利的API:
For some reason, Slauma's InverseProperty
attribute suggestion didn't work. What did work was me specifying the relationship between the two CaseStudy
navigation properties in AssessmentsCaseStudies
, and the CaseStudy
entity, via the Fluent API in my database context's OnModelCreating
method:
modelBuilder.Entity<AssessmentsCaseStudies>()
.HasRequired(acs => acs.CaseStudy)
.WithMany(cs => cs.AssessmentsCaseStudies)
.HasForeignKey(acs => acs.CaseStudyId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<AssessmentsCaseStudies>()
.HasOptional(acs => acs.Follows)
.WithMany() // No reverse navigation property
.HasForeignKey(acs => acs.FollowsCaseStudy)
.WillCascadeOnDelete(false);
在了加,这是生成的,当我迁移代码添加迁移
不再尝试添加 CaseStudy_CaseStudyId
列,我只是得到了 FollowsCaseStudyId
栏加入其中,相应的外键关系。
Once that's added, the migration code that's generated when I Add-Migration
no longer tries to add the CaseStudy_CaseStudyId
column and I just get the FollowsCaseStudyId
column added, with the appropriate foreign key relationship.
这篇关于为什么EF代码优先生成多余的外键列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!