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

6

我查了谷歌,但没找到好的资料。 我正在寻找在MVC中使用传统SQL查询而不是使用Entity Framework等。 如果您能提供一些示例代码会很好。

我开始学习MVC,但很多例子都使用linqEF等技术,而我完全不想使用它们,我想在Model层中使用简单的旧版SQL查询。


5
请不要简称ASP.NET MVC为"MVC",因为一个是框架,而另一个是独立于语言的设计模式。这就像把IE称作"互联网"一样。请改正用词。 - tereško
4个回答

11

最简单的例子:

//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" />
}

谢谢,您的意思是我应该将这段代码放入类的方法中,然后创建该类的对象,在控制器中调用该方法,例如classOBJ.sqlFun();? - user3111824
好的先生,但是如何在视图中访问它?就像我们在Web表单中使用GridView等一样,帮帮我。 - user3111824
@user3111824,你创建ViewModel并将其作为模型发送到View。然后,你告诉View它是一个强类型视图,其模型类型为你的ViewModel类。 - Aniket Inge
好的,请给我5分钟时间,我会给您提供一个例子。 - Aniket Inge
@user3111824,你好,我已经为“创建”视图、领域模型、视图模型和控制器逻辑编写了基本概述。 - Aniket Inge
不知道这个答案是否仍然适用。我遇到了与原帖相同的问题,仍然找不到一个合适的教程来将数据库连接到MVC而不使用Entity Framework。 - chemical_elii

0

使用实体框架可以完成

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

0
所以只需添加一个Helper类并编写所需内容(Sql连接,命令,查询...),然后从控制器调用这些帮助方法。这与旧风格没有区别。
静态Helper类:
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


你是指那些默认命名为delete、update等的4、5个类吗? - user3111824
不,我的意思是在你的一个类中编写所有方法,这样更优雅。等一下,我会添加一个示例。 - Selman Genç
示例:您好,这是一段程序相关的英文内容,需要翻译成中文。 - user3111824
请在控制器中调用,并在视图层中查看。 - user3111824

0

如何编写存储过程并将其作为方法调用,只需在项目中添加一个Linq to Sql Class,这将使处理数据库变得更加容易。
在创建所需的存储过程后:

  • 右键单击您的项目,然后添加新项,选择Linq to SQL Class并命名它
  • 拖放您之前制作的存储过程
  • 创建Linq to Sql Class的实例

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


只需要将您的存储过程拖放到“LinQ to SQL类”中,然后在代码中实例化此类即可。 - Aya Mohammad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接