5

Im, new in ASP MVC and I don't know how to create Models which base on stored procedures from my db. I have already database which works with another application, and my web page must use mentioned db.

I would be gratefull if someone can show me some piece of code describing the proper way how to do that. (if I wasnt clear: I need to create ASP .NET Models which use stored procedures from my database and nothing more)

txh in advance

4 Answers 4

6

@fgeorgiew are you just needing to know how to populate a model (class) from a stored procedure? You could use an ORM like NHibernate or Entity Framework to handle the plumbing for you, or just use raw ADO.NET code, like in the example below. Note, this is just rough code, but you get the idea.

public class MyModel
{
    public int ModelId { get; set; }
    public string FirstName { get; set; }
}

public class SqlMyModelRespoitory : IMyModelRepository // optional for DI/IoC, assume interface with GetSingleModel method
{
    public MyModel GetSingleModel()
    {
        MyModel model;
        string connString = "server=10.1.1.1;database=MyDb;uid=me;pwd=hidden";
        using (SqlConnection conn = new SqlConnection(connString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "p_GetMyModelFromDb";

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        model = new MyModel 
                        {
                           ModelId = Convert.ToInt32(reader[0]),
                           FirstName = reader[1].ToString()
                        };
                    }
                }
            }
        }
        return model;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

what if i want to get all the objects?
3

You could start with some abstraction indicating your intent:

public interface IMyRepository
{
    SomeModel Get(int id);
}

then you could write an implementation which will use your stored procedure:

public class MyRepositorySql: IMyRepository
{
    public SomeModel Get(int id)
    {
        ... call your stored procedure
    }
}

then design your controller so that it takes this abstraction as argument:

public class MyController: Controller
{
    private readonly IMyRepository _repository;
    public MyController(IMyRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index(int id)
    {
        var model = _repository.Get(id);
        return View(model);
    }
}

Now all that's left is to configure your DI framework to pass the proper implementation into the controller's constructor. As you can see now the controller is completely decoupled from the way data is fetched. It doesn't really matter whether you are using StoredProcs, some ORM or whatever in your data access layer.

2 Comments

You left me behind with 1 sec.
thx :) i think i get it. now it's a time to implement that and see results
1

How to call stored procedure in Asp.Net MVC

using System;
using System.Collections.Generic;
using System.IO;
using System.Data;
using System.Data.Entity;
using System.Net;
using System.Data.SqlClient;

public partial class StudentRecord
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Marks { get; set; }
    public string Grade { get; set; }
    public Nullable<System.DateTime> DOB { get; set; }
}

public class SqlMyModelRespoitory : First_Test_DBEntities 
{
    public StudentRecord GetSingleModel()
    {
        StudentRecord model;
        string connString = @"Paste Your Local Connection String";

        using (SqlConnection conn = new SqlConnection(connString))
        {
            conn.Open();

            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "InsertStudent";

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        model = new StudentRecord
                        {
                            Id = Convert.ToInt32(reader[0]),
                            Name = reader[1].ToString(),
                            Marks = reader[1].ToString(),
                            Grade = reader[1].ToString(),
                            DOB = Convert.ToDateTime(reader[1])
                        };
                    }
                }
            }
        }
        return model;
    }
}

Comments

0

Okay, lets say that you have a SP called Customers which is selecting some columns like:

ID
Name
Address

Now you will create a Model class inside your Model folder called "Customer.cs" and define the properties like:

public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }

This is your MODEL class.

1 Comment

thx 4 reply, but i think you didnt understand me properly :) I know what model is from RoR or Php etc and the problem is not about mapping C# Model Class to Db table but problem is about how to do that using stored procedures from my database and ADO .NET. (about the last one im not rly sure) :)

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.