我在下面遇到错误,并且不明白为什么,因为数据库中确实存在DepartmentID列,这是我的代码
基本上我有两个相关的表(1)具有PK DepartmentID的Departments和(2)具有FK DepartmentID的Departments_Category_Registration
控制器
public async Task<IActionResult> Index(string Categories)
{
ViewData["Dept"] = "No Records Found!";
Categories = Categories.Replace("_", " ");
//CHECK FOR INTEGER
try
{ Int32.Parse(Categories); }
catch //(Exception err)
{ }
if (Categories != null)
{
if (Categories.Trim() != "")
{
Categories = Categories.ToLower().Trim();
// DATABASE 2 - Main records
var DataContext2 = _context.Departments_Category_Registration.Include(c => c.Departments)
.Where(r => r.Departments.Department_Name == Categories).Select(u => new Departments_Category_Registration
{
CategoryID = u.CategoryID,
Category_Name = u.Category_Name,
DepartmentID = u.DepartmentID,
Description = u.Description
});
ViewData["Dept"] = Categories;
return View(await DataContext2.ToListAsync());
};
};
var DataContext = _context.Departments_Category_Registration.Include(c => c.Departments);
return View(await DataContext.ToListAsync());
}
//错误消息
return View(await DataContext2.ToListAsync());
SqlException: Invalid column name 'DepartmentsDepartmentID'.
答案 0 :(得分:0)
在[ForeignKey]
类中使用Departments_Category_Registration
批注,如下所示:
1。在从属类的外键属性上,传入导航属性的名称:
public class Departments_Category_Registration
{
[Key]
public int CategoryID { get; set; }
[ForeignKey("Departments ")]
public int DepartmentID { get; set; }
public Departments Departments { get; set; }
}
2。在依赖类的导航属性上,传入外键属性的名称:
public class Departments_Category_Registration
{
[Key]
public int CategoryID { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID ")]
public Departments Departments { get; set; }
}