Asp.net mvc MVC 5从SQL Server检索数据
有人能解释一下我是如何从SQL Server 2012数据库中检索一组简单的记录以显示在ASP.NET页面上的吗?我试着跟随一些教程,但我错过了一些东西,我看不见树木 我在Asp.net mvc MVC 5从SQL Server检索数据,asp.net-mvc,navigation,sql-server-2012,Asp.net Mvc,Navigation,Sql Server 2012,有人能解释一下我是如何从SQL Server 2012数据库中检索一组简单的记录以显示在ASP.NET页面上的吗?我试着跟随一些教程,但我错过了一些东西,我看不见树木 我在web.config文件中有一个连接字符串: <add name="DefaultConnection" connectionString="Data Source=MY-LAPTOP;Initial Catalog=Test;Integrated Security=True" provid
web.config
文件中有一个连接字符串:
<add name="DefaultConnection"
connectionString="Data Source=MY-LAPTOP;Initial Catalog=Test;Integrated Security=True"
providerName="System.Data.SqlClient" />
我有一个Shared/_layout.cshtml
页面,其中包含以下代码:
@model List<WebApplication1.Models.Navigation>
@foreach (var item in Model) {
<li>@Html.DisplayFor(modelItem => item.title_TV)</li>
}
我得到以下错误
App_Web_wqu1n0vj.dll中发生类型为“System.NullReferenceException”的异常,但未在用户代码中处理
我创建了一个名为testenties.cs
的类,如下所示:
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace WebApplication1.Models
{
public partial class TestEntities : DbContext
{
public TestEntities()
: base("name=DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Navigation> Navigations { get; set; }
}
使用系统;
使用System.Data.Entity;
使用System.Data.Entity.Infrastructure;
命名空间WebApplication1.Models
{
公共部分类测试实体:DbContext
{
公共测试()
:base(“name=DefaultConnection”)
{
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
抛出新代码FirstException();
}
公共虚拟数据库集导航{get;set;}
}
}
任何帮助都将不胜感激:-)您还应该有一个从
DbContext
派生的类-该类将定义正在使用的连接字符串,并且从错误消息中,我猜它没有使用DefaultConnection
,您已经(但还有其他内容)我添加了一个新类,请参阅修订后的帖子,不幸的是,我仍然得到同样的错误。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace WebApplication1.Models
{
public partial class TestEntities : DbContext
{
public TestEntities()
: base("name=DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Navigation> Navigations { get; set; }
}