gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:41:14 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com