Search code examples
c#asp.netasp.net-mvcasp.net-mvc-5ado.net-entity-data-model

How to Convert object result model to a custom view model in asp .net MVC 5


I had done a project of using stored procedure to display join table values using entity framework. I had done all the basic procedure and while calling it from my model it successfully return the object result,

Now my problem is I cannot able to convert that result model from stored procedure which is of complex return type to my view model. Can some one help me in solving it.

I had attached my project workings below,

This is the auto generated context by ADO .net Entity model

enter image description here

Edit function in model browser function imports

enter image description here

Display result which is auto generated.

enter image description here

This is what i'm trying to do

enter image description here

And this is the error I'm getting

enter image description here

This is how my view model consist of

enter image description here

Stored procedure query (Mysql)

enter image description here


Solution

  • As mentioned in the comment by OP the schema of employee and employee_details is something like:

    public class employee
    {
        public string Name {get;set;}
        public string Department {get;set;}
    }
    
    public class employee_details
    {
        public string Address {get;set;}
        public string Mobile {get;set;}
    }
    

    So, after applying the mapping your code would look something like:

    var query = objEmployee.sp_display().Select(s=> new ViewModel{
    employees = new employee{
     Name = s.Name //change the s.Name to the property name coming from your SP(if different)
     Department = s.Department
    },
    employee_detail = new employee_detail{
      Address = s.Address,
      Mobile = s.Mobile
    }}).ToList()
    

    Or Better just remove the query object and use the listEmployeeList as this list itself is also referencing the ViewModel so the query object is un-necessary(unless you want to do some other filtration on it) :

    listEmployeeList = // the above code with .ToList();