2015-01-21 52 views
1

我的工作,让功能简介页面来显示每个学生入学时间,但我得到这个错误:“实体类型没有定义键”异常

enter image description here

+1

错误不言自明。您在学生实体中缺少主键。你能不能粘贴你的学生实体类 – qamar 2015-01-21 05:45:33

+0

我在SQL上没有在Visual Studio中做过DB,所以我做了什么是从模型中单击EF设计师从DB,然后我从SQL获得相同的DB。无论如何,我为学生分配了一个主键。感谢您的帮助 – wadbarca 2015-01-21 05:58:17

+0

如果您在模型中定义了一个键,则此错误无意义。 – qamar 2015-01-21 06:06:08

回答

0

实体框架区分不同的对象在它们的关键字的上下文中。问题是Student实体没有定义任何键。如果你是第一次使用的代码也许你没有关注任何约定的主键 惯例是这样

public int EntityNameID {get;set;} 

public int Id {get;set;} 

Code First infers that a property is a primary key if a property on a class is named “ID” (not case sensitive), or the class name followed by "ID". If the type of the primary key property is numeric or GUID it will be configured as an identity column.

,你也可以指定[Key][1]属性到你想要的属性成为您的实体的关键。

另一种方法是使用流利的API定义您的实体的关键。

modelBuilder.Entity<Student>.HasKey(s => s.Id); 
+0

(加法)如果它不遵循此规则,则可以用属性[Key]修饰属性。 – Andreas 2015-01-21 05:59:45

+0

我首先从SQL服务器使用数据库如何使用您的建议修复它? – wadbarca 2015-01-21 06:00:51

+0

您应该修改您的数据库并为您的表定义一个主键@wadbarca – dotctor 2015-01-21 06:01:32

相关问题