【问题标题】:Entity Framework code first one-to-zero relationshipEntity Framework 代码第一个一对零关系
【发布时间】:2015-07-23 00:24:35
【问题描述】:

我正在尝试在餐桌人员和部门之间建立一对零的关系。

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

    // other fields

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

    public virtual Department Department { get; set; }
}

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

    public virtual Staff Staff{ get; set; }
}

当我运行这段代码时,它给出了这个错误:

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

【问题讨论】:

  • 这没什么用,因为我已经在类中声明了外键属性。
  • 阅读答案,你使用的ForeignKeyAttribute错了。将其添加到导航属性而不是整数。
  • 你能告诉我这样做的正确方法吗?因为我听不懂。

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


【解决方案1】:

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

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

    public virtual Staff Staff{ get; set; }
}

【讨论】:

  • 没什么区别
【解决方案2】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 2018-03-08
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多