【问题标题】:using simple queries in ASP.NET MVC在 ASP.NET MVC 中使用简单查询
【发布时间】:2013-12-25 11:42:24
【问题描述】:

我查了谷歌,但没有发现什么好东西。我在 MVC 中搜索 usinf 传统 SQL 查询,而不是实体框架等。所以如果你们提供一些例子会很好。

我开始学习MVC,但很多示例使用linqSQLEF 等我根本不想使用,我想在模型中使用简单的旧SQL 查询层。

【问题讨论】:

  • 请不要将“ASP.NET MVC”简单地称为“MVC”。一种是框架,另一种是与语言无关的设计模式。这就像调用 IE - “互联网”

标签: c# sql asp.net-mvc


【解决方案1】:

最简单的例子:

//Domain Class
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace BanjoOnMyKnee.Models
{
    public class DomainModel
    {
        public string connectionString = ".\\SQLEXPRESS; Initial-Catalog=YourDBName; Integrated-Security=true";
        public void CreateSomething(ViewModel model)
        {
            using(SqlConnection connection = new SqlConnection(connectionString))
            using (SqlCommand command = new SqlCommand("",connection))
            {
                command.CommandText = "insert into Names values(@Name)";
                command.Parameters.AddWithValue("@Name", model.Name);
                command.ExecuteNonQuery();
            }
        }

        public ViewModel FindSomething(int id)
        {
            var model = new ViewModel();
            using (SqlConnection connection = new SqlConnection(connectionString))
            using (SqlCommand command = new SqlCommand("", connection))
            {
                command.CommandText = "select * from Names where Id=@Id";
                command.Parameters.AddWithValue("@Id",id);
                SqlDataReader reader = command.ExecuteReader();
                model.Id = id;
                model.Name = reader["Name"].ToString();
            }
            return model;
        }

        public void DeleteSomething(ViewModel model)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            using (SqlCommand command = new SqlCommand("", connection))
            {
                command.CommandText = "delete from Names where Id=@Id";
                command.Parameters.AddWithValue("@Id", model.Id);
                command.ExecuteNonQuery();
            }
        }

        public void EditSomething(ViewModel model)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            using (SqlCommand command = new SqlCommand("", connection))
            {
                command.CommandText = "Update Names set Name=@Name where Id=@Id";
                command.Parameters.AddWithValue("@Name", model.Name);
                command.Parameters.AddWithValue("@Id", model.Id);
                command.ExecuteNonQuery();
            }
        }
    }
}

这是我的控制器类

//My Controller class
public class HomeController : Controller
{
    //
    // GET: /Home/

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

    //
    // GET: /Home/Create

    public ActionResult Create()
    {
        return View(new ViewModel());
    }

    //
    // POST: /Home/Create

    [HttpPost]
    public ActionResult Create(ViewModel vm)
    {
        try
        {
            var domainModel = new DomainModel();
            domainModel.CreateSomething(vm);
            return RedirectToAction("Index");
        }
        catch
        {
            return View(new ViewModel());
        }
    }

    //
    // GET: /Home/Edit/5

    public ActionResult Edit(int id)
    {
        ViewModel model = new DomainModel().FindSomething(id);
        return View(model);
    }


    [HttpPost]
    public ActionResult Edit(ViewModel editModel)
    {
        try
        {
            var dm = new DomainModel();
            dm.EditSomething(editModel);
            return RedirectToAction("Index");
        }
        catch
        {
            return View(new ViewModel());
        }
    }
 }

我的 ViewModel 类

//My ViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BanjoOnMyKnee.Models
{
    public class ViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

还有我的“创建”视图

//My view
@model BanjoOnMyKnee.Models.ViewModel

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using(Html.BeginForm()){
    @Html.HiddenFor(m => m.Id);
    <p> Name : 
        Html.EditorFor(m=>m.Name);</p>
    <input type="submit" value="Create" />
}

【讨论】:

  • 谢谢,你的意思是我应该将 htis 代码放入类的方法中,然后应该使该类的对象在 COntroller 中调用该方法,如 classOBJ.sqlFun(); ?
  • 好的先生,但是如何在 VIEW 中访问它?就像我们在网络表单中一样,使用 gridview 等,帮助
  • @user3111824 你制作 ViewModel 并将其作为模型发送到 View。然后你告诉视图它是一个强类型视图,具有你的 ViewModel 类的模型类型。
  • 好,给我5分钟,我再给你举个例子
  • @user3111824 那里,我已经为“创建”视图、域模型、视图模型和控制器逻辑编写了一个基本大纲
【解决方案2】:

如何编写存储过程并将它们作为方法调用,只需将LinQ to Sql Class 添加到您的项目中,这将使处理数据库变得更加容易
制作所需的存储过程后:

  • 在您的项目中右键单击然后添加新项目,然后选择一个 LinQ to SQL 类并命名它
  • 拖放您之前制作的存储过程
  • 创建linq to sql class 的实例

然后你可以调用你的存储过程和这个类的成员
http://msdn.microsoft.com/en-us/library/bb386946(v=vs.110).aspx 此链接也可能对您有所帮助

【讨论】:

  • 只需将存储过程拖放到您的“LinQ to SQL 类”中,然后在您的代码中创建此类的实例
【解决方案3】:

所以只需添加一个Helper class 并编写您需要的任何内容(Sql 连接、命令、查询...),然后从您的控制器调用这些辅助方法。它与旧样式没有什么不同

静态助手类:

public static class HelperFunctions
{
    private static string connString = "your connection string";

    public static IEnumerable<User> GetAllUsers()
    {
        using (var conn = new SqlConnection(connString))
        using (var cmd = new SqlCommand(connection:conn))
        {
            // set your command text, execute your command 
            // get results and return
        }
    }

在您的控制器中:

public ActionResult Users()
    {
      // Get user list
        IEnumerable<User> users = HelperFunctions.GetAllUsers();

        // Return your view and pass it to your list
        return View(users);
    }

在您的视图中设置您的视图模型:

@model IEnumerable<User>

然后您可以从您的视图中访问您的用户列表,例如:

foreach(var user in Model)
{
   <p> @user.Name </p>
}

Model 代表你的实际视图模型。如果你想从你的视图中访问多个列表,你可以使用 ViewBag 或 ViewData。查看这篇文章了解更多信息:http://www.codeproject.com/Articles/476967/WhatplusisplusViewData-2cplusViewBagplusandplusTem

【讨论】:

  • 你的意思是那些默认命名为删除、更新等的4,5个类?
  • 不,我的意思是在你的一个类中编写所有方法它更优雅,等我添加一个示例。
  • 例子将不胜感激先生
  • 请添加来自控制器的调用并在 VIEW 层查看
【解决方案4】:

使用实体框架可以做到

Entitiesdb db = new Entitiesdb();
string query="delete from tableA where id=@id"
db.Database.ExecuteSqlCommand(query, @id);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    相关资源
    最近更新 更多