c# - Entity Framework 代码优先一对零关系

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

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

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

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

The property 'DepartmentID' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type.

最佳答案

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

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

    public virtual Staff Staff{ get; set; }
}

关于c# - Entity Framework 代码优先一对零关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30185621/

相关文章:

c# - 如何在一个模型中选择不同表格的内容

c# - 是否有任何时区实际正确使用 TimeZoneInfo IsFixedDateRule?

c# - ASP.NET Core 托管的 Blazor 模板中的授权问题

c# - 我会通过将新值 [] 分配给填充数组来导致内存泄漏吗

c# - C# Parent 和 Child 中的 MDI 窗体

c# - 如何在 ASP.Net MVC C# 中的 Form Post 上绑定(bind) List<T>

javascript - 如何更改此 JS 脚本以发出 "GET"而不是 "POST"调用

c# - 如何仅使用一个 Controller 动态检索表?

c# - 对于 EF 上下文,实例变量和局部变量哪个更好?

c# - JsonConverter 和 EntityData