我正在尝试查询一个 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/