[英]Entity Framework - Invalid Column Name 'User_ID"
I have a project written with C#
on the top of ASP.NET MVC 5 framework. 我在ASP.NET MVC 5框架的顶部有一个用C#
编写的项目。 I am using Entity Framework 6.2 ORM to interact with my database. 我正在使用Entity Framework 6.2 ORM与我的数据库进行交互。
I have the following 2 entity classes 我有以下2个实体类
public class User
{
[Key]
public int Id { get; set;}
public string FirstName { get; set; }
public int? MainClassRoomId { get; set; }
// ....
[ForeignKey("MainClassRoomId")]
public virtual ClassRoom MainClassRoom { get; set; }
public virtual ICollection<ClassRoom> AvailableClassRooms { get; set; }
}
public class ClassRoom
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Title { get; set; }
public int UserId { get; set; }
// ....
[ForeignKey("UserId")]
public virtual User Instructor { get; set; }
}
I find a single user with no problem like this 我找到一个没有问题的用户
User user = DataContext.Users.FirstOrDefault(x => x.Id == 10);
However, if I want to access the MainClassRoom
navigation property I get the following error 但是,如果我要访问MainClassRoom
导航属性, MainClassRoom
出现以下错误
Invalid column name 'User_Id'. 无效的列名“ User_Id”。
I get the above error after I execute the following 执行以下命令后出现上述错误
if(user.MainClassRoom != null)
{
// Some something with user.MainClassRoom
}
What could be causing this error? 是什么导致此错误? How can I fix it? 我该如何解决?
Try adding the foreign key attribute to the ICollection navigation property: 尝试将外键属性添加到ICollection导航属性:
[ForeignKey("UserId")]
public virtual ICollection<ClassRoom> AvailableClassRooms { get; set; }
Since you've changed the naming convention you must set it on both sides of the relationship. 由于更改了命名约定,因此必须在关系的两侧都进行设置。
I usually prefer to do this using EF's fluent API as it's more flexible and you don't end up using magic strings. 我通常更喜欢使用EF的流畅API来执行此操作,因为它更灵活,而且您最终不会使用魔术字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.