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);
}
}
}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..
1 Reply
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Rupesh KahanePosted Jul 2, 2018, 8:45 AM
Note: Plz insure that whenever columns you are returning from the prcedures that model has to be declared in it.