C# 在ASP.NET MVC中使用简单查询

C# 在ASP.NET MVC中使用简单查询,c#,sql,asp.net-mvc,C#,Sql,Asp.net Mvc,我查了谷歌,但没发现什么好东西。我在MVC中搜索usinf传统的SQL查询,而不是实体框架等。所以,如果你们能给我提供一些示例,那就太好了 我开始学习MVC,但是很多示例使用linq到SQL和EF等我根本不想使用的,我想在模型层使用简单的SQL查询 最简单的例子: //Domain Class using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using

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

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

最简单的例子:

//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" />
}
//我的视图
@模型BanjoOnMyKnee.Models.ViewModel
@{
ViewBag.Title=“创建”;
}
创造
@使用(Html.BeginForm()){
@HiddenFor(m=>m.Id);
姓名:
EditorFor(m=>m.Name)

}
所以只需添加一个
助手类
并编写您需要的任何内容(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
        }
    }
公共静态类HelperFunctions
{
私有静态字符串connString=“您的连接字符串”;
公共静态IEnumerable GetAllUsers()
{
使用(var conn=new SqlConnection(connString))
使用(var cmd=new SqlCommand(连接:conn))
{
//设置命令文本,执行命令
//获取结果并返回
}
}
在控制器中:

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

        // Return your view and pass it to your list
        return View(users);
    }
public ActionResult用户()
{
//获取用户列表
IEnumerable users=HelperFunctions.GetAllUsers();
//返回视图并将其传递到列表
返回视图(用户);
}
在视图中设置视图模型:

@model IEnumerable<User>
@model IEnumerable
然后,您可以从视图访问用户列表,例如:

foreach(var user in Model)
{
   <p> @user.Name </p>
}
foreach(模型中的var用户)
{
@user.Name

}

Model
表示实际的视图模型。如果您想从视图中访问多个列表,可以使用ViewBag或ViewData。有关详细信息,请参阅本文:

编写存储过程并将其作为方法调用,只需在项目中添加
LinQ to Sql类即可更易于处理数据库
完成所需的存储过程后:

  • 在项目中单击鼠标右键,然后添加新项,然后选择一个LinQ to SQL类并将其命名
  • 拖放以前生成的存储过程
  • 为您的
    linqtosql类创建一个实例
然后可以调用存储过程和此类的成员

此链接也可以帮助您使用实体框架来完成

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

你是指那些默认命名为delete、update等的4,5个类吗?不,我是指在你的一个类中编写所有方法。它更优雅,等等,我将添加一个示例。示例将不胜感激。Sir请添加控制器的调用和查看视图层库,你的意思是我应该将htis代码放入类的方法中,然后对象调用控制器中的该方法,如classOBJ.sqlFun()好的,先生,那么如何在视图中访问它呢?就像我们在webforms中使用gridview等,Help@user3111824创建ViewModels并将其作为模型发送到视图。然后告诉视图它是强类型视图,具有ViewModel类的模型类型。好的,给我5分钟时间,我会带着example@user3111824那里我已经为“创建”视图、域模型、视图模型和控制器逻辑写了一个基本大纲。所有需要做的就是将存储过程拖放到您的“LinQ to SQL类”中,然后在代码中创建这个类的实例。请不要简单地将“ASP.NET MVC”称为“MVC”一个是框架,另一个是独立于语言的设计模式。这就像把IE称为“互联网”