Pea*_*arl 5 c# asp.net entity-framework
当我使用以下代码时,使用主键和外键关系成功生成表.
[Table("tblDepartments")]
public class DepartmentModel
{
[Key]
public int DepartmentID { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public ICollection<EmployeeModel> Employees { get; set; }
}
[Table("tblEmployees")]
public class EmployeeModel
{
[Key]
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public virtual DepartmentModel DID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但是,当我使用以下代码时,我得到错误:
[Table("tblDepartments")]
public class DepartmentModel
{
[Key]
public int DepartmentID { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public ICollection<EmployeeModel> Employees { get; set; }
}
[Table("tblEmployees")]
public class EmployeeModel
{
[Key]
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
[ForeignKey("DeptID")]
public virtual DepartmentModel DID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
错误:
类型为"MvcApplication1.Models.EmployeeModel"的属性"DID"上的ForeignKeyAttribute无效.在依赖类型"MvcApplication1.Models.EmployeeModel"上找不到外键名称"DeptID".Name值应该是以逗号分隔的外键属性名称列表.
请帮忙.提前致谢.
小智 9
问题出在您的EmployeeModel上,因为您缺少Gert建议的表格中的离开字段.您可以将以下内容用于EmployeeModel
[Table("tblEmployees")]
public class EmployeeModel
{
[Key]
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public int DeptID { get; set; } //<-- You forgot to add this
[ForeignKey("DeptID")]
public virtual DepartmentModel DID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7107 次 |
| 最近记录: |