c# – 如何将DocumentDB查询作为List返回?
发布时间:2020-12-15 23:29:56 所属栏目:百科 来源:网络整理
导读:我正在尝试查询DocumentDB集合并通过一个安静的ASP.Net Web API控制器返回结果.我有一个名字和出生日期的简单运动员课程,以及包含这种方法的AthletesController: [HttpGet] public ListAthlete listAthletes() { string endpoint = ConfigurationManager.Ap
我正在尝试查询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; } 一般的想法是我将IQueryable转换为IEnumerable,将其转换为Type Athlete,然后使用ToList方法为Web API消费做好准备. 但是,这是我在运行时得到的错误:
解决方法
您将要使用通用的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(); 虽然这在我看来有点丑陋. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |