gpt4 book ai didi

c# - EntityType 没有键定义错误

转载 作者:IT王子 更新时间:2023-10-29 03:32:52 24 4
gpt4 key购买 nike

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 模型:

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; }
}
}

型号:

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;
}
}

数据库表:

CREATE TABLE [dbo].[studentdetails](
[RollNo] [int] NULL,
[Name] [nvarchar](50) NULL,
[Stream] [nvarchar](50) NULL,
[Div] [nvarchar](50) NULL
)

在 global.asax.cs 中

Database.SetInitializer<MvcApplication1.Models.studentContext>(null);

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

"One or more validation errors were detected during model generation" along with "Entity type has no key defined".

最佳答案

模型类应更改为:

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; }
}
}

关于c# - EntityType 没有键定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20203492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com