开发者

ef code first map subclasses to single foreign key

I can't find an answer to this anywhere, so here goes.

I have several subclassed "Answer" types. All answers will need a reference back to their question.

By default, when ef creates the "Answers" table, it creates one foreign key reference to the questions table called FullNameQuestion_QuestionId, and one called TextboxQuestion_QuestionId.

What I want is for TextboxQuestion and FullNameQuestion to both use the same QuestionId foreign key. I cannot figure out how to get the mapping to work for this.

   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> FullNameAns开发者_如何学Cwers { 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; }
    }

I tried adding a question id to the TextboxAnswer and FullNameAnswer classes like this, but it just creates two columns, QuestionId and QuestionId1. Is there any way to get these to share the same column?

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; }
    }


I played with it now little bit and it only confirmed my expectations. It is probably not possible. Columns mapped in derived entities must be unique among all entities in hierarchy. If I tried to remap relations to the same column I got exception saying that column with the same name was already used. The only shared columns can be defined in parent entity so until you move your navigation property to base Question and reference base Answer you will not achieve that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜