【问题标题】:ASP.Net MVC Application with SQL [closed]带有 SQL 的 ASP.Net MVC 应用程序 [关闭]
【发布时间】:2016-08-13 06:05:40
【问题描述】:

我有一个 MVC 应用程序,我试图从 ADO.Net 实体数据模型中获取 SQL,以显示在我的 index.cshtml

这个页面后面我的家庭控制器是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using TemplateBootstrap.Models;

namespace TemplateBootstrap.Controllers
{
    public class HomeController : Controller
    {
        private DBEntities db = new DBEntities();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";
            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
    }
}

在我的index.cshtml 中,目前我在我的导航标题和内容中硬编码了很多 HTML,这些内容存储在我的数据库的 5 个表中,例如主导航 1/2、侧导航 1/2 和内容。

下面是用于 MainNavLevel1 的 SQL 语句。 SELECT [MNavID], [DisplayLabel],[Priority] FROM [MainNavLevel1] ORDER BY [Priority]"

这是我使用一个没有 SQL 代码的表的示例。

controller: namespace TemplateBootstrap.Controllers
{
    public class NavigationController : Controller
    {
        private AskHoltsEntities db = new AskHoltsEntities();

        public ActionResult Index()
        {
            return View(db.AH_Corp_MainNavLevel1.ToList());
        }
    }
}

使用此视图:

@model IEnumerable<TemplateBootstrap.Models.AH_Corp_MainNavLevel1>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>@Html.DisplayNameFor(model => model.DisplayLabel)</th>
        <th>@Html.DisplayNameFor(model => model.URL)</th>
        <th>@Html.DisplayNameFor(model => model.Priority)</th>
        <th></th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td> @Html.DisplayFor(modelItem => item.DisplayLabel) </td>
        <td> @Html.DisplayFor(modelItem => item.URL)</td>
        <td> @Html.DisplayFor(modelItem => item.Priority)</td>
    </tr>
}
</table>

我需要帮助来更改代码或添加(类)以放置我的 SQL 语句以从多个表中检索数据。

【问题讨论】:

  • 有什么想法吗?
  • 你想做什么?您需要指定要在页面上显示的内容,以便我们了解目标。
  • 有什么问题?
  • 我应该把 SQL 查询放在哪里来帮助做到这一点?
  • 您使用的是 ORM 还是使用 ado.net?

标签: c# asp.net sql-server asp.net-mvc asp.net-mvc-4


【解决方案1】:

基本 ADO.NET 连接在 MVC 中根本没有真正改变。它们仍然依赖于诸如 SqlConnection 对象及其相关命令之类的东西,您可以在 MVC 中毫无问题地使用它们(只要您有连接字符串)。

如果您想构建一个简单的查询,如果您想在控制器操作(或将处理数据的抽象类)中定位特定表(可能/可能不在您的上下文中),它可能如下所示独占访问):

// Build your connection
using(var connection = new SqlConnection("{your-connection-string-here"}))
{
     // Build your query
     var query = "SELECT [MNavID], [DisplayLabel],[Priority] FROM [MainNavLevel1] ORDER BY [Priority]";
     // Create a command to execute your query
     using(var command = new SqlCommand(query,connection))
     {
          // Open the connection
          connection.Open();

          // Execute your query here (in this case using a data reader)
          using(var reader = command.ExecuteReader())
          {
                // Create a list of items to use in your View (assumes this class exists)
                var navigationLabels = new List<NavigationLabel>();

                // Iterate through your results
                while(reader.Read())
                {
                      // Build a navigation item for each row returned from
                      // your query
                      navigationLabels.Add(new NavigationLabel(){
                           MNavID = reader["MNavID"],
                           DisplayLabel = reader["DisplayLabel"],
                           Priority = reader["Priority"]
                      });
                }

                // Pass your labels to your View
                return View(navigationLabels);
          }
     }
}

这假设您有一个类实际上模仿了您的数据库结构并包含类似的属性,在这种情况下您可以映射到NavigationLabel

如果您正在使用 Entity Framework 之类的东西并且已经拥有这些实体,那么您大概可以使用类似以下代码的东西从上下文中提取您的适当项目:

using(var context = new DbEntities())
{
       var navigationLabels = context.NavigationLabels
                                     .OrderBy(n => n.Priority)
                                     .ToList();
       return View(navigationLabels);
}

【讨论】:

  • 嗨,这个代码在我的控制器中吗?因为这是我不确定应该去哪里?
  • 是的,你可以把它放在你的控制器中(或者如果你更喜欢抽象一点,你可以创建另一个类来处理数据访问并通过那个类调用它)。
  • 把数据层和业务逻辑分开抽象出来会更好
  • @jamiedanq 你能告诉我怎么做吗?
  • @RionWilliams 非常感谢您的回答我尝试添加 using (var context = new ....) 部分,但出现错误:(
【解决方案2】:

首先你需要声明你的 ApplicationDbContext 对象。 (提示:ApplicationDbContext 将派生自您在 startup.cs 或您可能拥有的任何地方的连接字符串。)我实际上在http://blog.meemsit.com/post/2016/04/03/how-to-make-a-mvc-web-application-using-asp-net5-mvc-6-and-entity-framework-7 有一篇博文分步教程我认为这可能会回答您的一些更深层次的问题你可能有。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using TemplateBootstrap.Models;

namespace TemplateBootstrap.Controllers
{
    public class HomeController : Controller
    {
        //private DBEntities db = new DBEntities();
        //This will provide your context to your HomeController
        private readonly ApplicationDbContext _context;

    //Then declare your public context.
    public HomeController(ApplicationDbContext context)
    {
        _context = context;
    }

        public ActionResult Index()
        {
            return View(_context.MainNavLevel1.ToList());
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";
            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
    }
}

然后转到您的 Index.cshtml 并在顶部调用您的模型并使用 Html 助手显示信息。

   @model IEnumerable<TemplateBootstrap.Models.MainNavLevel1>


<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.DisplayLabel)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Priority)
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.DisplayLabel)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Priority)
        </td>
    </tr>
}
</table>

并且你的模型文件夹中应该有一个 ApplicationDbContext 类,你可以在该文件夹中使用 fluentAPI 来定义有关如何连接的任何特殊内容。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity;
using TemplateBootstrap.Models;

namespace TemplateBootstrap.Models
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            //Put SQL Statements Here
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }
        public DbSet<Product> Product { get; set; }
    }
}

【讨论】:

  • 嗨,我的应用程序不喜欢 ApplicationDbContext _context;你知道为什么会这样吗?
  • 不喜欢哪个部分,ApplicationDbContext 还是 _context?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
  • 2013-05-25
  • 1970-01-01
  • 2010-10-30
相关资源
最近更新 更多