【问题标题】:ef code first map subclasses to single foreign keyef 代码首先将子类映射到单个外键
【发布时间】:2011-10-26 02:00:33
【问题描述】:

我在任何地方都找不到答案,所以就这样吧。

我有几个子类“答案”类型。所有答案都需要参考他们的问题。

默认情况下,当 ef 创建“Answers”表时,它会创建一个名为 FullNameQuestion_QuestionId 的问题表的外键引用和一个名为 TextboxQuestion_QuestionId 的外键引用。

我想要的是 TextboxQuestion 和 FullNameQuestion 都使用相同的 QuestionId 外键。我无法弄清楚如何让映射为此工作。

   public abstract class Question
    {     
        public int QuestionId { get; set; }
        private string Text { get; set; }
    }

public class TextboxQuestion : Question
{
    public string TextboxValue { get; set; }
    public virtual List<TextboxAnswer> TextboxAnswers { get; set; }        
}

public class FullNameQuestion : Question
{
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public virtual List<FullNameAnswer> FullNameAnswers { get; set; }
}

    public abstract class Answer
    {      
        public int AnswerId { get; set; }   
        public int UserId { get; set; }
    }

    public class TextboxAnswer : Answer
    {       
        public string TextboxValue { get; set; }
    }    

    public class FullNameAnswer:Answer
    { 
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
    }

我尝试像这样向 TextboxAnswer 和 FullNameAnswer 类添加问题 ID,但它只创建了两列 QuestionId 和 QuestionId1。有没有办法让这些共享同一列?

public class TextboxAnswer : Answer
    {
        [ForeignKey("Question")]
        public int QuestionId { get; set; }
        public virtual Question Question { get; set; }
        public string TextboxValue { get; set; }
    }


    public class FullNameAnswer:Answer
    {
        [ForeignKey("Question")]
        public int QuestionId { get; set; }
        public virtual Question Question { get; set; }

        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
    }

【问题讨论】:

    标签: entity-framework inheritance mapping entity-framework-4.1 ef-code-first


    【解决方案1】:

    我现在稍微玩了一下,它只是证实了我的期望。这可能是不可能的。在派生实体中映射的列在层次结构中的所有实体中必须是唯一的。如果我尝试将关系重新映射到同一列,我会收到异常说已经使用了同名的列。唯一的共享列可以在父实体中定义,因此在您将导航属性移动到基础 Question 并引用基础 Answer 之前,您将无法实现。

    【讨论】:

      猜你喜欢
      • 2016-10-28
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多