[RESOLVED]Cannot implicitly convert type 'System.Linq.IQueryable

I have the following error.

What I’m trying to do,  is doing a search from a MasterList Entitie and include my phone listlocation.

What is wrong with this code?

 var masterListss = from r in db.MasterLists.Include(m => m.PhoneListLocation)
                                          orderby r.LastName
                                          select r;

            if (!String.IsNullOrEmpty(SearchString)) {
                masterListss = masterListss.Where(s => s.LastName.Contains(SearchString));

                
                }

   Error 1 Cannot implicitly convert type 'System.Linq.IQueryable<WebApplicationTestCode.Models.MasterList>' to 'System.Linq.IOrderedQueryable<WebApplicationTestCode.Models.MasterList>'. An explicit conversion exists (are you missing a cast?) C:PhoneListApplicationWebApplicationTestCodeControllersMasterListsController.cs 28 32 WebApplicationTestCode

Now this work but trying to do a orderby r.LastName  Not sure how to tackle this

 var masterListss = from r in db.MasterLists.Include(m => m.PhoneListLocation)
                                          //orderby r.LastName
                                          select r;

            if (!String.IsNullOrEmpty(SearchString)) {
                masterListss = masterListss.Where(s => s.LastName.Contains(SearchString));

Hi,

Remove the 

orderby r.LastName and test it again

you can do the order by 

in this line 

 masterListss = masterListss.Where(s => s.LastName.Contains(SearchString));

You can try just using method syntax (since you are already using it for the Include() method :

var masterListss = db.MasterLists.Include(m => m.PhoneListLocation)
                                 .OrderBy(m => m.LastName);

Likewise if you need it to be descending, you can just use :

var masterListss = db.MasterLists.Include(m => m.PhoneListLocation)
                                 .OrderByDescending(m => m.LastName);

Or you could just handle your logic in one area when defining your lists :

// Test for your Searching string
if(!String.IsNullOrEmpty(SearchString))
{
       var masterListss = db.MasterLists.Include(m => m.PhoneListLocation)
                                        .Where(m => m.LastName.Contains(SearchString))
                                        .OrderBy(m => m.LastName);
}
else
{
       var masterListss = db.MasterLists.Include(m => m.PhoneListLocation)
                                        .OrderBy(m => m.LastName);
}

Leave a Reply