c# - 如何将 DocumentDB 查询作为 List<Type> 返回?

标签 c# asp.net-web-api azure-cosmosdb

我正在尝试查询一个 DocumentDB 集合并通过一个 Restful ASP.Net Web API Controller 返回结果。我有一个带有姓名和出生日期的简单 Athlete 类,以及一个包含此方法的 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;

        }

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

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

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

最佳答案

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

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

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

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

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

关于c# - 如何将 DocumentDB 查询作为 List<Type> 返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34521706/

相关文章:

javascript - 如何在版本 ^3 上使用 gremlin 启动与 Cosmos DB 图形数据库的新连接

c# - 如何处理非 fatal error 情况

c# - 扩展 ApiController

json - postman :发送嵌套的 JSON 对象

azure - 更新 Azure CosmosDB 分区键和分区键值

azure - 以编程方式对现有集合进行范围索引

c# - Microsoft Report Viewer 2012 异常 "Not enough storage is available to process this command"

c# - 添加 ADO.NET 实体模型崩溃

c# - 如何遍历 JsonResult 方法返回的字典?

c# - InRequestScope 无法在 ExceptionLogger 上下文中工作