Programming Solutions

Your Source for Information

Cannot Implicitly Convert Type IQueryable

by Maeenul 25. January 2012 09:29

Cannot implicitly convert type 'System.Linq.IQueryable<DBTestTool.Models.TEST>' to 'System.Collections.Generic.IList<DBTestTool.Models.TEST>'. An explicit conversion exists (are you missing a cast?)

clip_image002[4]

Let me explain the scenario where I got this error message.

 IList<TEST> tests = db.TESTs.Where(t => t.VIEW_ID == testTemplate.VIEW_ID && String.IsNullOrEmpty(t.TEMPLATE_FILE_NAME));

 

I have a DBContext named db and one entity is TESTS. I just want to find some specific tests that mathces with some criteria. The first and ultimate solution to this is to use Where() function in Lambda Expression. The where function uses the condition inside it and matches all the items in the entity object and returns the matching items. As my items are of TEST type, I am trying to hold it in a IList<TEST>, which is quite logical. But I face an error as mentioned at the top.

 

Cannot implicitly convert type 'System.Linq.IQueryable<DBTestTool.Models.TEST>' to 'System.Collections.Generic.IList<DBTestTool.Models.TEST>'. An explicit conversion exists (are you missing a cast?)

So it says that I need to do and explicit conversion. Why?

This is because lambda expressions are deferred execution expressions just as LINQ. When we write the lambda expression, it is immediately executed. That’s why it returns IQueryable<Test>, not IList<TEST>. So we need to explicitly cast it to IList<TEST>.

Solution to this error:

Solution 1:

 

IList<TEST> tests = (IList<TEST>)db.TESTs.Where(t => t.VIEW_ID == testTemplate.VIEW_ID && String.IsNullOrEmpty(t.TEMPLATE_FILE_NAME));

 

Just as the error says, use an explicit casting to IList<TEST>. It will force the execution to be done at that time.

 

Solution 2:

 

IList<TEST> tests = db.TESTs.Where(t => t.VIEW_ID == testTemplate.VIEW_ID && String.IsNullOrEmpty(t.TEMPLATE_FILE_NAME)).ToList();

 

Other than casting it, we can also call the ToList() method over the IQueryable<TEST>. This will also allow us to get the immediate execution and return the IList<TEST>.

 

So, whenever you use lambda expression that you might think should return an IList<>, you will actually have to cast it and use ToList() to the actual list.

 

 

Tags:

Category: C#



Add comment

biuquote
  • Comment
  • Preview
Loading

Alpha Tags