0

I have an IQueryable object that I want to cast into a JObject.

I tried to run JObject.Parse(myIQueryableObject) but receive the error:

Cannot convert from 'System.Linq.IQueryable<bunchOfStuffThatICantIncludeHere>' to 'string'

What is the best approach here?

GSerg
  • 76,472
  • 17
  • 159
  • 346
ddastrodd
  • 710
  • 1
  • 10
  • 22
  • Can you share the code you're working with? – Dortimer May 15 '19 at 15:57
  • @Dortimer Unfortunately, I am restricted in what I can share here. – ddastrodd May 15 '19 at 16:04
  • You want JObject.FromObject(), I think - And you probably want to .ToList() your IQueryable<> first! – Sam May 15 '19 at 16:06
  • @Sam That's the ticket! Thanks a lot. This did the trick. – ddastrodd May 15 '19 at 16:08
  • Since `IQueryable` is a collection the root JSON container will be a `JArray` not a `JObject`. But you can just use `JToken.FromObject()` as shown in [Can Json.Net handle a `List`?](https://stackoverflow.com/a/20769644), [Serialize an object directly to a JObject instead of to a string in json.net](https://stackoverflow.com/a/44896383), [Could not determine JSON object type for type “Class”](https://stackoverflow.com/a/40728452/3744182). Do those answer your question? – dbc May 15 '19 at 22:51

1 Answers1

1

You should run like so:

JObject.Parse(myIQueryableObject.ToList());

IQueryable will not return all the results from the database until they are called, they can be used for deferred execution. So executing ToList() will return all the results from the DB.

A good source here: What's the difference between IQueryable and IEnumerable

andyb952
  • 1,931
  • 11
  • 25