C# 如何将DocumentDB查询作为列表返回<;类型>;?

C# 如何将DocumentDB查询作为列表返回<;类型>;?,c#,asp.net-web-api,azure-cosmosdb,C#,Asp.net Web Api,Azure Cosmosdb,我试图查询DocumentDB集合,并通过restful ASP.NETWebAPI控制器返回结果。我有一个带有姓名和出生日期的简单运动员类,以及一个包含以下方法的AthletesController: [HttpGet] public List<Athlete> listAthletes() { string endpoint = ConfigurationManager.AppSettings["endpoint"];

我试图查询DocumentDB集合,并通过restful ASP.NETWebAPI控制器返回结果。我有一个带有姓名和出生日期的简单运动员类,以及一个包含以下方法的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;

        }
[HttpGet]
公开名单运动员()
{
字符串端点=ConfigurationManager.AppSettings[“端点”];
字符串authkey=ConfigurationManager.AppSettings[“authkey”];
字符串数据库=ConfigurationManager.AppSettings[“数据库”];
字符串集合=“运动员”;
DocumentClient客户端=新DocumentClient(新Uri(端点),authkey);
List response=client.CreateDocumentQuery(“dbs/”+数据库+“/colls/”+集合,“从运动员中选择*).AsEnumerable().Cast().ToList();
返回响应;
}
一般的想法是,我将IQueryable转换为IEnumerable,将其转换为类型Athleter,然后使用ToList方法为Web API消费做好准备

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

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


您需要使用泛型CreateDocumentQuery方法,而不是非泛型方法。这样修改代码应该会得到您想要的结果:

List response=client.CreateDocumentQuery(“dbs/”+数据库+“/colls/”+集合,“从运动员中选择*).ToList();
或者,您也可以执行以下操作,尽管我尚未对此进行测试:

List response=client.CreateDocumentQuery(“dbs/”+database+“/colls/”+collection,“从运动员中选择*)。选择(doc=>JsonConvert.DeserializeObject(doc.ToString()))。ToList();

虽然在我看来这有点难看。

你有没有试过只做ToList()是的,那不会编译。错误CS0029无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”嗯,我认为下一个逻辑步骤将是执行linq选择,因为您已经将结果转换为enemurable。只需尝试选择并构建删除的集合。直接演员可能不太可能知道,你的第一个建议非常有效!