EntityType 'UserInfo' has no key defined. Define the key for this EntityType.

One or more validation errors were detected during model generation:

 System.Data.Edm.EdmEntityType: : EntityType 'UserInfo' has no key defined. Define the key for this EntityType.  System.Data.Edm.EdmEntitySet: EntityType: EntitySet �UserInfo� is based on type �UserInfo� that has no keys defined.

遇见这个问题,我觉得很奇特,因为事实上我已经为'UserInfo'这个类定义了[KEY]的类注释。

然后又提示我找不到Key。见下面的代码

复制代码
 1     public class UserInfo
 2     {
 3         [Key]
 4         public int UserID;
 5         public string UserName;
 6         public string Password;
 7         public int UseState;
 8         public string Email;
 9         public DateTime AddTime;
10         public int AddUser_ID;
11         public string ImgUrl;
12         public virtual UserType UserTypes { get; set; }
13     }
复制代码

后面在stackoverflow上找到了答案EF会自动识别一个实体的主键只要主键的名称符号 'Id'或 '实体名Id'. 另外,它必须声明成属性,访问权限必须是Public的。这个错误是因为我将UserId声明成了一个字段,只要修改成属性就OK了。修改后的代码如下所示。

 

复制代码
 1     public class UserInfo
 2     {
 3         [Key]
 4         public int UserID { get; set; }
 5         public string UserName { get; set; }
 6         public string Password { get; set; }
 7         public int UseState { get; set; }
 8         public string Email { get; set; }
 9         public DateTime AddTime { get; set; }
10         public int AddUser_ID { get; set; }
11         public string ImgUrl{ get; set; }
12         public virtual UserType UserTypes { get; set; }
13     }
复制代码

 

 

 

 

2013-01-10  16:50:05

posted @   陈哈哈  阅读(9036)  评论(2编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
点击右上角即可分享
微信分享提示