我正在尝试将我的ASP.Net MVC(VS2013)链接到我的SQL Server(SQL Server 2014 Mgt Studio)但是失败了!这是我设置的代码,但是我在ResultsView中得到'System.Data.Entity.ModelConfiguration.ModelValidationException',或者表中的数据没有显示出来。任何帮助将不胜感激 - 我已附上我的代码:
型号:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GlobalMetricsTest2.Models
{
public class GMUSALong
{
public virtual int BID { get; set; }
public virtual string BMetrics { get; set; }
public virtual string BTopic { get; set; }
}
}
上下文:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GlobalMetricsTest2.Models;
using System.Data.Entity;
namespace GlobalMetricsTest2.DAL
{
public class GMUSALongContext : DbContext
{
public DbSet<GMUSALong> GMTest { get; set; }
}
}
控制器:
using System.Web;
using System.Web.Mvc;
using GlobalMetricsTest2.DAL;
using GlobalMetricsTest2.Models;
namespace GlobalMetricsTest2.Controllers
{
public class GMUSALongController : Controller
{
private GMUSALongContext db = new GMUSALongContext();
public ActionResult Index()
{
var advItems = db.GMTest;
return View(advItems.ToList());
}
}
}
查看:
@model IEnumerable<GlobalMetricsTest2.Models.GMUSALong>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<table>
<tr>
<th>ID</th>
<th>Metrics</th>
<th>Topic</th>
</tr>
@foreach (GlobalMetricsTest2.Models.GMUSALong item in Model)
{
<tr>
<td>@item.BID:</td>
<td>@Html.DisplayFor(modelItem => item.BMetrics)</td>
<td>@Html.DisplayFor(modelItem => item.BTopic)</td>
</tr>
}
</table>
答案 0 :(得分:0)
从初学者的角度来看,我建议你尝试另一种方法。根据需要创建数据库表。然后导航到New - &gt;创建一个模板化的MVC项目。单击Project,选择ASP.NET Web Application。系统将提示您进一步选择,选择&#39; MVC&#39;。这将为您提供一个很好的模板示例,您可以参考任何MVC问题。创建新项目并使用NUGET添加MVC 5将启动一个更清晰的示例,但需要更多步骤。
现在您已经创建了自己的网站。右键点击你的模特&#39;文件夹,添加 - &gt;在New Item中,选择ADO.NET Entity Data Model,系统会提示您提供更多选项,从数据库中选择Code First,提供数据库连接信息,并选择您要导入的对象。此时,您应该拥有一个功能数据上下文,其中包含分配给非标准命名约定的所有必需注释。
现在右键点击您的观看次数&#39;文件夹,添加 - &gt; &#39;新的脚手架项目&#39;,选择&#39; MVC 5查看&#39;,为您的观点命名(我推荐您的模型&#39;查看&#39;) ,选择您要使用的型号,选择您要创建的屏幕类型,这将是“列表”。一旦创建,您将拥有一个很好的标准示例,其中包含您要学习的所有部分。一旦您获得了所需的知识,您就可以对此过程进行微调,以便为您的网站快速创建功能强大的屏幕。
http://www.asp.net/visual-studio/overview/2013/aspnet-scaffolding-overview