列名称无效' QuestionGroup_QuestionGroupID'

时间:2015-01-02 20:34:41

标签: c# asp.net-mvc entity-framework entity-framework-6

我有一个.NET,MVC 5,EF 6 Code First项目。基本上,在使用EF将对象保存到数据库时,我得到了{"Invalid column name 'QuestionGroup_QuestionGroupID'."}QuestionGroup是模型,它与具有外键QuestionGroupID的子模型有关系。其密钥的名称为QuestionGroupID,在模型及其对应的表中。

模特:

public class QuestionGroup
{
    [Key]
    [Required]
    public Int32 QuestionGroupID { get; set; }
    //Other properties omitted for brevity

    public Guid MasteryObjectiveID { get; set; }
    public virtual MasteryObjective MasteryObjective {
        //Necessary because this model is in a different context/db and EF doesn't support that.
        get { return DAL.DatabaseMethods.GetMasteryObjective(MasteryObjectiveID); }
    }
    public virtual List<MultipleChoiceQuestion> Questions{ get; set; }
}

MasteryObjective没有QuestionGroup的外键,因为它是从QuestionGroups到MasteryObjectives的多对一关系。问题模型如下所示:

public abstract class Question
{
    [Key]
    [Required]
    public Int32 QuestionID { get; set; }
    //Other properties omitted for brevity

    public Int32 QuestionGroupID { get; set; }
    public virtual QuestionGroup QuestionGroup { get; set; }
}

//Use this attribute whenever inheriting from an abstract class so EF will create separate tables for each.
[Table("MultipleChoiceQuestion")]
public class MultipleChoiceQuestion : Question
{
    public List<MultipleChoiceAnswer> Answers { get; set; }
}

我得到的外部异常是DbUpdateException was unhandled by user code,内部异常是Invalid column name 'QuestionGroup_QuestionGroupID'.

从数据库方法保存错误的地方抛出错误,如

context.QuestionGroup.Add(qg); context.SaveChanges();

这种方法已经有一段时间没有改变了,我很确定那里没有错。

我接下来应该尝试什么?

1 个答案:

答案 0 :(得分:0)

该列可能不存在于数据库中。如果您正在使用迁移,请尝试从包管理器运行update-database

也可以帮助浏览数据库,验证它是否正确命名。如果它是其他东西,你可以像这样装饰键:

[Key]
[Required]
[Column("QuestionGroupID")] // Change this to whatever the column is named
public Int32 QuestionGroupID { get; set; }