Cannot create and populate list type System.Linq.IQueryable

While working on creating a client application to consume a MVC WebApi, I kept running into following error when I tried to read response as a collection object, more specifically as IQueryable object.

Cannot create and populate list type System.Linq.IQueryable
at Newtonsoft.Json.Utilities.CollectionUtils.CreateList(Type listType, Boolean& isReadOnlyOrFixedSize)

I thought there was something wrong in my object model itself which is causing construction of the collection object to fail. I tried to simplify model to the point where I created a class with only one property. And I still kept getting exception. Then looking at the exception message, it was clear that message is not generated by .Net/MVC framework. It is definitely being generated by JSON.Net library. So I opened up the source code of that library and here what I found.

CreateList and CreateAndPopulateList methods in the library do not support creation of collection object of type IQueryable. Following code shows the workflow of the method.

if (listType.IsArray)
{.....}
else if (ReflectionUtils.InheritsGenericDefinition
 (listType, typeof(ReadOnlyCollection<>), out collectionType))
{.....}
else if (typeof(IList).IsAssignableFrom(listType))
{.....}
else if (ReflectionUtils.ImplementsGenericDefinition(listType, typeof(ICollection<>)))

if (list == null)
        throw new Exception("Cannot create and populate list type {0}.".
           FormatWith(CultureInfo.InvariantCulture, listType));

As you can see from this code that if you are asking the library to create a collection of type IQueryable, it is going to fall through all the checks and eventually the function will throw exception because it could not create collection object.

I will not call that this is a bug in JSON.Net library. It is that it is kind of a limitation. One improvement I could see in this exception is that message needs to be more clear in specifying that argument type is not correct or in the message specify what are expected types for this method.

To fix my code, I switched to using IEnumerable or IList instead of IQueryable collection type when reading WebApi response.

comments powered by Disqus

Search

Social

Weather

9.0 °C / 48.3 °F

weather conditions Clouds

Monthly Posts

Blog Tags