简体   繁体   English

实体框架代码优先将表链接在一起外键问题

[英]Entity Framework Code First Linking tables together foreign key issue

3 Tables (Only relevent columns shown for brevity) such that; 3个表(为简洁起见,仅显示相关列);

[QuestionSet]
<int>       Id (Pk)
...

[Link_Set_to_Question]
<int> Id (pk)
<int> fk_Question <-- Foreign key to Questions Table
<int> fk_SetId <-- Foreign key to Questions Table
<int> DisplayOrder
...

[Questions]
<int> Id (Pk)
...

My entity Models. 我的实体模型。

public class QuestionSet
{
    [Key]
    public int Id { get; set; }
    ...

    [ForeignKey("fk_SetId")]
    public virtual ICollection<Link_Set_to_Question> QuestionSet { get; set; }

    public QuestionSetDetails()
    {
        this.QuestionSet = new List<Link_Set_to_Question>();                                  
    }
}

public class Link_Set_to_Question
{
    [Key]
    public int Id { get; set; }
    public int fk_SetId { get; set; }
    public int fk_QuestionId { get; set; }

    [ForeignKey("Id")]
    public virtual Questions Question { get; set; }

    public Relations_Questions_To_Sets()
    {
        this.Question = new Questions();
    }
}

When I add in the second class, then the Question Entries are all null. 当我添加第二个类时,问题条目全部为空。 Presumably because it is trying to map the Id of Questions to the Primary Key of Link_Set_to_Question not to fk_QuestionId. 大概是因为它试图将问题ID映射到Link_Set_to_Question的主键而不是fk_QuestionId。

So, is there a way of structuring my objects / attributes so that this will work, or do I need to delve into the ModelBuilder. 因此,有没有一种结构化我的对象/属性的方法,以便可以正常工作,或者我是否需要深入研究ModelBuilder。 (In which case, how do I define it such that Set has many links objects, and each link object has one question?) (在那种情况下,如何定义Set包含许多链接对象,而每个链接对象都有一个问题?)

 modelBuilder
            .Entity<QuestionSet>()
            .HasMany<Link_Set_to_Question>(set => set.QuestionSet)
            .WithRequired(linkSet => linkSet.Question)
            .HasForeignKey(linkSet => linkSet.fk_QuestionId)
            .WillCascadeOnDelete(true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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