Home  »  Articles  »  ASP.Net MVC  »

Cannot implicitly convert type ‘System.Linq.IQueryable’ to ‘System.Collections.Generic.IEnumerable’.

 Posted By : Manoranjan SahooPosted Date : 07/09/2014 04:29:17 PM Category : ASP.Net MVC Points : 8

In my last project i found the below error while trying to get the data through LINQ.

My Query was :
var model = (from e in dc.Users
                     join j in dc.UserRights on e.rightsLevel equals j.Id
                     select new { username = e.username, 
                                  ID = e.Id, 
                                  FullName = e.FullName, 
                                  RightsLevel = j.RightsLevel });
ERROR:
Cannot implicitly convert type ‘System.Linq.IQueryable<AnonymousType#1to ‘System.Collections.Generic.IEnumerable’. An explicit conversion exists (are you missing a cast?)

When we try to select specific column via LINQ queries or Lamda Expression in MVC C# class, we sometimes got the above error. Because we can’t use Anonymous return type in C# Model class, so it throws an error.

To solve this issue use object as return type, so it lets you select specific columns from SQl server table.

SOLUTION:
First i have created one class explicitly with name “UsersViewModel” containing properties (username,ID,FirstName,RightsLevel). Then modified LINQ query and method as below.

See below ex :
public IEnumerable<UsersViewModel> Index()
{
     ContactDataContext dc = new ContactDataContext();
     var model = (from e in dc.Users
             join j in dc.UserRights on e.rightsLevel equals j.Id
                 select new UsersViewModel
                 {
                    username = e.username, 
                    ID = e.Id, 
                    FullName = e.FullName,
                    RightsLevel = j.RightsLevel
                  }).AsEnumerable();
     return model;
}

Hope this will help you.


Responses
No responses found for this thread. Be the first to respond this thread.
Post Reply
Login to post Response.