Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a DocumentDB Query as List<Type>?

I'm trying to query a DocumentDB collection and return the results through a restful ASP.Net Web API controller. I have a simple Athlete class with name and date of birth, and an AthletesController that contains this method:

  [HttpGet]
        public List<Athlete> listAthletes()
        {

            string endpoint = ConfigurationManager.AppSettings["endpoint"];
            string authkey = ConfigurationManager.AppSettings["authkey"];
            string database = ConfigurationManager.AppSettings["database"];
            string collection = "Athletes";

            DocumentClient client = new DocumentClient(new Uri(endpoint), authkey);

            List<Athlete> response = client.CreateDocumentQuery("dbs/" + database + "/colls/" + collection, "SELECT * FROM Athletes").AsEnumerable().Cast<Athlete>().ToList();

            return response;

        }

The general thinking is that I convert the IQueryable into an IEnumerable, cast it to Type Athlete, then use the ToList method to get it ready for Web API consumption.

However, this is the error I get at runtime:

Unable to cast object of type 'Microsoft.Azure.Documents.QueryResult' to type 'TestApp.Models.Athlete'

like image 582
Graham Avatar asked Nov 09 '25 03:11

Graham


1 Answers

You're going to want to use the generic CreateDocumentQuery method instead of the non generic. Modifying your code like so should yield the results you're looking for:

List<Athlete> response = client.CreateDocumentQuery<Athlete>("dbs/" + database + "/colls/" + collection, "SELECT * FROM Athletes").ToList();

Alternatively, you can likely, although i haven't tested this, do the following:

List<Athlete> response = client.CreateDocumentQuery("dbs/" + database + "/colls/" + collection, "SELECT * FROM Athletes").Select(doc => JsonConvert.DeserializeObject<Athlete>(doc.ToString())).ToList();

Although this is a little uglier in my opinion.

like image 107
Jonathon Chase Avatar answered Nov 11 '25 09:11

Jonathon Chase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!