首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >EntityType没有键定义错误

EntityType没有键定义错误
EN

Stack Overflow用户
提问于 2013-11-26 05:16:23
回答 13查看 309.8K关注 0票数 149

控制器:

代码语言:javascript
复制
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模型:

代码语言:javascript
复制
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; }
    }
}

模型:

代码语言:javascript
复制
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;
    }
}

数据库表:

代码语言:javascript
复制
CREATE TABLE [dbo].[studentdetails](
    [RollNo] [int] NULL,
    [Name] [nvarchar](50) NULL,
    [Stream] [nvarchar](50) NULL,
    [Div] [nvarchar](50) NULL
)  

global.asax.cs中的

代码语言:javascript
复制
Database.SetInitializer<MvcApplication1.Models.studentContext>(null);

上面的代码列出了我正在处理的所有类。在运行我的应用程序时,我收到以下错误:

“在模型生成期间检测到一个或多个验证错误”以及“实体类型未定义关键字”。

EN

回答 13

Stack Overflow用户

回答已采纳

发布于 2013-12-02 00:36:35

Model类应更改为:

代码语言:javascript
复制
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace MvcApplication1.Models
{
    [Table("studentdetails")]
    public class student
    {
        [Key]
        public int RollNo { get; set; }

        public string Name { get; set; }

        public string Stream { get; set; }

        public string Div { get; set; }
    }
}
票数 177
EN

Stack Overflow用户

发布于 2014-02-28 20:01:38

  1. 确保学生类的公共成员定义为属性 w/ {get; set;} (您的是公共变量-一个公共的[Key]批注,位于您选择的属性之上。
票数 103
EN

Stack Overflow用户

发布于 2015-04-03 14:32:13

发生这种情况有几个原因。其中一些是我发现的here,另一些是我自己发现的。

  • 如果属性的名称不是Id,则需要向其中添加[Key]属性。
  • 键必须是属性,而不是字段。
  • 键必须是CLS兼容的类型,这意味着无符号类型(如uint、<代码>d13uint>等)不是CLS错误也可能由CLS引起。
票数 84
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20203492

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档