Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
using System.ComponentModel.DataAnnotations.Schema;
namespace MvcApplication1.Controllers
{
public class studentsController : Controller
{
//
// GET: /students/
public ActionResult details()
{
int id = 16;
studentContext std = new studentContext();
student first = std.details.Single(m => m.RollNo == id);
return View(first);
}
}
}
DbContext Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcApplication1.Models
{
public class studentContext : DbContext
{
public DbSet<student> details { get; set; }
}
}
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
namespace MvcApplication1.Models
{
[Table("studentdetails")]
public class student
{
public int RollNo;
public string Name;
public string Stream;
public string Div;
}
}
Database table:
CREATE TABLE [dbo].[studentdetails](
[RollNo] [int] NULL,
[Name] [nvarchar](50) NULL,
[Stream] [nvarchar](50) NULL,
[Div] [nvarchar](50) NULL
)
In global.asax.cs
Database.SetInitializer<MvcApplication1.Models.studentContext>(null);
上面的代码列出了我正在处理的所有类 . 运行我的应用程序时收到错误:
“在模型生成期间检测到一个或多个验证错误”以及“实体类型没有定义键” .
12 回答
这可能有几个原因 . 其中一些我找到here,其他我自己发现的 .
如果属性的名称不是
Id
,则需要为其添加[Key]
属性 .密钥需要是属性,而不是字段 .
关键需要
public
密钥需要是符合CLS的类型,这意味着不允许使用无符号类型,如
uint
,ulong
等 .此错误也可能由configuration mistakes引起 .
我知道这篇文章很晚但是这个解决方案帮助了我:
在[Key]之后添加[Column(Order = 0)]可以按增量加1:
等等...
在我的情况下,我在使用实体框架创建“带视图的MVC 5控制器”时遇到错误 .
我只需要在创建Model类之后构建项目,而不需要使用[Key]注释 .
使用[key]对我来说不起作用,但使用id属性就可以了 . 我只是在我的课堂上添加这个属性 .
EF框架提示'no key'的原因是EF框架需要数据库中的主键 . 要以声明方式告知EF键的属性,可以添加
[Key]
注释 . 或者,以最快的方式添加ID
属性 . 然后,EF框架默认将ID
作为主键 .该对象必须包含一个将用作
Primary Key
的字段,如果您有一个名为Id
的字段,则默认情况下这将是Entity Framework将链接到的对象的主键 .否则,您应该将
[Key]
属性添加到您想要用作Primary Key
的字段上方,并且还需要添加命名空间System.ComponentModel.DataAnnotations
:https://stackoverflow.com/a/51180941/7003760
Model类应更改为:
确保学生 class 的公共成员被定义为 properties w /
{get; set;}
(你的公开 variables - 一个常见的错误) .在所选属性的顶部放置
[Key]
注释 .您不必一直使用键属性 . 确保映射文件正确地解决了密钥
and don't forget to add the mapping in the Repository's OnModelCreating
另外请记住,不要忘记添加 public 这样的关键字
你必须使用这样的Public关键字
一切都是对的,但就我而言,我有两个这样的课
删除上层课程后,它对我来说很好 .
对我来说,模型很好 . 那是因为我有2个 different versions 的实体框架 . Web项目的一个版本和包含模型的公共项目的另一个版本 .
我只是 consolidate the nuget packages .
请享用!