【发布时间】:2018-12-31 12:40:56
【问题描述】:
我最近在 Course 表中添加了一个名为“CreatedBy”的列,它引用了数据库中用户表中的 UserID 并为其创建了相应的实体字段。但是在访问 CreatedBy 字段时出现错误: System.Data.SqlClient.SqlException:列名“CreatedByID”无效。
我尝试了不同的数据注释方式,但没有奏效。
实体:
public partial class Course
{
public Course()
{
this.CourseLessons = new List<CourseLesson>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourseID { get; set; }
public string CourseName { get; set; }
public string CourseDescription { get; set; }
public int? CreatedByID { get; set; }
[ForeignKey("CreatedByID")]
public virtual WebsiteUser CreatedBy { get; set; }
public virtual ICollection<CourseLesson> CourseLessons { get; set; }
}
public partial class WebsiteUser
{
public WebsiteUser()
{
// Other code
}
[Key]
public int UserID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
}
public ActionResult EditCourse()
{
SQLContext context = new SQLContext();
var deletethis = context.Courses.First().CreatedBy; // Gives error
return View(context.Courses);
}
【问题讨论】:
-
您的实体类型是什么?数据库优先还是代码优先?你更新你的数据库和迁移了吗?
标签: c# entity-framework model-view-controller foreign-keys