实体框架代码首先是一对一关系

时间:2015-05-12 08:32:01

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

我正在尝试在员工和部门之间建立一对一的关系。

chrome.runtime.getBackgroundPage(function (backgroundPage){
  chrome.app.window.current().onClosed.addListener(function(){
    console.log("This won't appear anywhere since (this.)console doesn't exist anymore");
    backgroundPage.console.log("This will appear in the background page console, which you can open from the Extensions settings page");
  });
});

当我运行此代码时,它会出现此错误:

  

属性“DepartmentID”无法配置为导航属性。该属性必须是有效的实体类型,并且该属性应具有非抽象的getter和setter。对于集合属性,类型必须实现ICollection,其中T是有效的实体类型。

2 个答案:

答案 0 :(得分:0)

像这样更改你的模型,现在你可以使用DepartmentID作为外键

public class Department
{
    [Key]
    public int DepartmentID { get; set; }
    public string Name { get; set; }

    public virtual Staff Staff{ get; set; }
}

答案 1 :(得分:0)

试试这个:

public class Staff
{
    public int ID { get; set; }

    // other fields    

    public int DepartmentID { get; set; }

    [ForeignKey("DepartmentID")]
    public virtual Department Department { get; set; }
}

naming is correct起,我认为您也可以尝试删除ForeignKeyAttribute。有关详细信息,请参阅:http://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx