在我的 mvc 项目中,我想使用 Entity Framework 添加一个带有 View 的 Controller 。我正在使用本教程进行操作 http://www.asp.net/mvc/overview/getting-started/introduction/accessing-your-models-data-from-a-controller
我多次重建我的项目。我尝试了一些在互联网上找到的解决方案,例如 Adding A New MVC 5 Controller with Views Using Entity Framework Scaffolding Error 或重新安装我的 nuget 包,重新启动 Visual Studio,检查我的 conecctiong 字符串(顺便说一句,这似乎没问题),添加新模型等。我不知道下一步该做什么,这就是我向您寻求帮助的原因。
我使用:
- Windows 7 上的 Visual Studio 2013
- .NET Framework 4.6.2
我的模型代码:
public class UserResModel
{
[Display(Name = "ReservationID")]
public int ReservationID { get; set; }
[Display(Name = "Class")]
public string ClassName { get; set; }
[Display(Name = "When")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime ClassWhen { get; set; }
[Display(Name = "Cancel reservation")]
public bool CancelRes { get; set; }
最佳答案
您需要将“Key”属性添加到您的 ReservationID 属性。脚手架在自动生成 Controller 代码时需要一个 Key 才能工作。
[Key]
[Display(Name = "ReservationID")]
public int ReservationID { get; set; }
添加后,重建项目并再次尝试脚手架。
关于c# mvc 5 添加 Controller 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39692887/