6

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 good if you guys provide me some examples.

I started to learn MVC but lot of examples uses linq to SQL and EF etc which I don't want to use at all, I want to use simple old SQL queries in Model layer.

tereško
  • 58,060
  • 25
  • 98
  • 150
user3111824
  • 173
  • 2
  • 4
  • 11
  • 5
    Please, stop referring to "ASP.NET MVC" simply as "MVC". One is a framework, while other is a language-independent design pattern. It's like calling IE - "the internet" – tereško Dec 26 '13 at 12:19

4 Answers4

11

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" />
}
Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
  • thanks, u mean that i should put htis code into class' method and then should make object of that class to call that method in COntroller like classOBJ.sqlFun(); ? – user3111824 Dec 25 '13 at 11:58
  • ok sir but then how to access it in VIEW ? like we do in webforms, using gridview etc , Help – user3111824 Dec 25 '13 at 12:01
  • @user3111824 you make ViewModels and send it to the View as a model. And then you tell the view that it is a strongly typed view, with a model type of your ViewModel class. – Aniket Inge Dec 25 '13 at 12:02
  • Ok, give me 5 minutes, I will come back to you with an example – Aniket Inge Dec 25 '13 at 12:04
  • @user3111824 there, I have written a basic outline for 'create' view, the domain model, the viewmodel and the controller logic – Aniket Inge Dec 25 '13 at 12:49
  • wonder if this answer is still applicable. I'm having the same problem like the op. still can't find a proper tutorial connecting database to mvc without the use of Entity Framework – chemical_elii Jun 01 '17 at 08:27
0

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

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

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

Aya Mohammad
  • 245
  • 3
  • 13
  • all what will need is to drag and drop your stored procedures into ur 'LinQ to SQL class` then just make instance of this class in your code – Aya Mohammad Dec 25 '13 at 12:19
0

Using entity framework it can be done

Entitiesdb db = new Entitiesdb();
string query="delete from tableA where id=@id"
db.Database.ExecuteSqlCommand(query, @id);
Imran
  • 1,951
  • 1
  • 10
  • 7