I have a problem with ASP.NET Core scaffolding. I just applied scaffolding on a simple relational model and I got this SqlException.
Microsoft.Data.SqlClient.SqlException: 'Invalid column name 'ClassRoomClassId'.'
All I have two models
ClassRoom
public class ClassRoom
{
[Key]
public int ClassId { get; set; }
public string ClassName { get; set; }
public virtual ICollection<Student> Student { get; set; }
}
Student
public class Student
{
[Key]
public int StuId { get; set; }
public string StuName { get; set; }
[ForeignKey("ClassId")]
public int? ClassId { get; set; }
public ClassRoom ClassRoom { get; set; }
}
And I get the exception when executing Students/Index.
// GET: Students
public IActionResult Index()
{
return View(_context.Student.ToList());
}
I have no column with this name 'ClassRoomClassId' !!
what would be the problem?
Try changing [ForeignKey("ClassId")]
to [ForeignKey("ClassRoom")]
or placing it on ClassRoom
property:
public class Student
{
...
public int? ClassId { get; set; }
[ForeignKey("ClassId")]
public ClassRoom ClassRoom { get; set; }
}