Fazil Basheer

Fazil Basheer

  • NA
  • 24
  • 1.2k

ASP.NET MVC5 Stored Procdure Output Error

Jul 1 2018 12:15 AM
1.Stored Procedure
USE [College]
GO

ALTER PROCEDURE [dbo].[Usp_Employee]
    @Mode TINYINT =NULL
AS
BEGIN
    IF @Mode=1
    BEGIN
        SELECT  EmplId,EmplName,EmpRole,Salary from [dbo].[Employee]
        ORDER BY EmplName;
    END
    ELSE IF @Mode=2
    BEGIN
        SELECT  EmplId,EmplName from [dbo].[Employee]
        ORDER BY EmplName;
    END
END
 
 2.Employee (Model Class)
 
namespace MVCQuestion.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Employee
    {
        public short EmplId { get; set; }
        public string EmplName { get; set; }
        public string EmpRole { get; set; }
        public Nullable<int> Salary { get; set; }
    }
}
 
 3.View Page
 
@model IEnumerable<MVCQuestion.Models.Employee>

@{
    ViewBag.Title = "Index";
}

<h2>Employee Name and Role </h2>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.EmplName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.EmpRole)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.EmplName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.EmpRole)
        </td>
    </tr>
}

</table>
 
4.Controller
 
using MVCQuestion.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCQuestion.Controllers
{
    public class EmployeeController : Controller
    {
        CollegeEntities objDbContext = new CollegeEntities();
        // GET: Employee
        public ActionResult Index()
        {
            var Query = "exec [dbo].Usp_Employee @Mode=2";
            var Output = objDbContext.Database.SqlQuery<Employee>(Query).ToList<Employee>();
            return View(Output);
        }
    }
}
 5.Error
 
The data reader is incompatible with the specified 'CollegeModel.Employee'. A member of the type, 'EmpRole', does not have a corresponding column in the data reader with the same name.
 
 
 
I am used a single stored procedure to get all the columns inside Employee and also to get only 2 columns by passing Mode variable. in the above code i used mode 2 get two columns from Employee table where EmpRole & Salary skipped . Ok my Question is ,Is there any way to get only 2 parameters from stored procedure and Stored into new Employee model class list without making an additional class that is,any way to get data ino Employee model class list object without initialising all the variables inside the Employee model class. thanks..
 
 
 

Answers (1)