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.

1
  • 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" Commented Dec 26, 2013 at 12:19

4 Answers 4

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" />
}
Sign up to request clarification or add additional context in comments.

6 Comments

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(); ?
ok sir but then how to access it in VIEW ? like we do in webforms, using gridview etc , Help
@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.
Ok, give me 5 minutes, I will come back to you with an example
@user3111824 there, I have written a basic outline for 'create' view, the domain model, the viewmodel and the controller logic
|
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

1 Comment

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

4 Comments

you mean those 4,5 classes which are named as delete, update etc by default ?
no,i mean write all method in your one class it is more elegant,wait i will add a sample.
example would be much appreciated sir
please add calling from controller's and viewing on VIEW layer
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.