如何将ListDB查询作为List <Type>返回?

Gra*_*ham 3 c# asp.net-web-api azure-cosmosdb

我正在尝试查询DocumentDB集合并通过一个安静的ASP.Net Web API控制器返回结果.我有一个名字和出生日期的简单运动员课程,以及包含这种方法的AthletesController:

  [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;

        }
Run Code Online (Sandbox Code Playgroud)

一般的想法是我将IQueryable转换为IEnumerable,将其转换为Type Athlete,然后使用ToList方法为Web API消费做好准备.

但是,这是我在运行时得到的错误:

无法将"Microsoft.Azure.Documents.QueryResult"类型的对象强制转换为"TestApp.Models.Athlete"类型

Jon*_*ase 7

您将要使用通用的CreateDocumentQuery方法而不是非泛型方法.像这样修改你的代码应该产生你正在寻找的结果:

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

或者,您可以,尽管我没有测试过,但请执行以下操作:

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

虽然这在我看来有点丑陋.