using simple queries in ASP.NET MVC

后端 未结 4 1498
遇见更好的自我
遇见更好的自我 2020-12-29 16:03

I checked google but found nothing good. I am searching for usinf Traditional SQL queries in MVC instead of Entity framework etc. So it would be go

相关标签:
4条回答
  • 2020-12-29 16:35

    So just add a Helper class and write whatever you need (Sql connections,commands,queries...), then call these helper methods from your controller.It's not different than old style

    Static Helper Class:

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

    In your Controller:

    public ActionResult Users()
        {
          // Get user list
            IEnumerable<User> users = HelperFunctions.GetAllUsers();
    
            // Return your view and pass it to your list
            return View(users);
        }
    

    In your View set your View model:

    @model IEnumerable<User>
    

    Then you can access your user list from your View, for example:

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

    Model represents your actual View Model.If you want access more than one list from your View, you can use ViewBag or ViewData. Check this article for more information: http://www.codeproject.com/Articles/476967/WhatplusisplusViewData-2cplusViewBagplusandplusTem

    0 讨论(0)
  • 2020-12-29 16:41

    Using entity framework it can be done

    Entitiesdb db = new Entitiesdb();
    string query="delete from tableA where id=@id"
    db.Database.ExecuteSqlCommand(query, @id);
    
    0 讨论(0)
  • 2020-12-29 16:42

    Simplest example:

    //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();
                }
            }
        }
    }
    

    And here's my controller class

    //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());
            }
        }
     }
    

    My ViewModel class

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

    And my 'Create' View

    //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" />
    }
    
    0 讨论(0)
  • 2020-12-29 16:49

    how about writing stored procedures and just invoke them as methods using by just adding a LinQ to Sql Class into your project this will make it much easier for dealing with database
    after making the needed stored procedures :

    • right click in your project then add new item then choose a LinQ to SQL Class and name it
    • drag and drop your previously made stored procedures
    • make an instance of your linq to sql class

    then you can invoke your stored procedures and members of this class
    http://msdn.microsoft.com/en-us/library/bb386946(v=vs.110).aspx this link may help you as well

    0 讨论(0)
提交回复
热议问题