首页 > 解决方案 > 我想在我的 asp.net web api 应用程序中按 id 过滤 firebase realtime-database,但我不知道如何构建查询

问题描述

我正在开发一个带有 firebase 实时数据库的 asp.net web api 项目。我使用 firebaseclient 库。但我想知道如何使用 firebase 客户端开发查询。

我已经创建了获取所有供应商的查询。这是工作。

另一个通过 id 获取供应商。它给出了语法错误。这是行不通的。

//method to get all suppliers. Working properly
[Route("getAll")]
public async Task<HttpResponseMessage> GetSuppliers()
{
    var firebaseClient = new FirebaseClient(<firebase url>);

    //Retrieve data from Firebase
    var suppliers = await firebaseClient
    .Child("suppliers")
    .OnceAsync<SupplierModel>();

     List<SupplierModel> supplierList = new List<SupplierModel>();

     foreach (var sup in suppliers)
     {
         supplierList.Add(sup.Object);
     }
     HttpResponseMessage response;
     response = Request.CreateResponse(HttpStatusCode.OK, supplierList);
     return response;
}

//method to filter by id. Have syntax errors

[Route("addSuppllier/{supplierId}")]
public async Task<HttpResponseMessage> GetSupplierById([FromUri] string supplierId)
{
    var firebaseClient = new FirebaseClient(<firebase url>);

    //Retrieve data from Firebase
    var suppliers = await firebaseClient
    .Child("suppliers")
    .OrderBy("supplierId")
    .EqualTo(supplierId);
    List<SupplierModel> supplierList = new List<SupplierModel>();
    foreach (var sup in suppliers)
    {
        supplierList.Add(sup.Object);
    }
    HttpResponseMessage response;
    response = Request.CreateResponse(HttpStatusCode.OK, supplierList);
    return response;
}

第一个查询正确检索所有供应商。第二个查询有语法错误。

标签: c#asp.netfirebase-realtime-database

解决方案


您可以尝试使用这种方法。

FirebaseResponse response = await firebaseClient.GetAsync("suppliers");
JObject jsonResponse = response.ResultAs<JObject>();

var query = new List<SupplierModel>();
if (jsonResponse != null)
{
foreach (var item in jsonResponse)
        {
         var value = item.Value.ToString();
         var supplierModel = JsonConvert.DeserializeObject<SupplierModel>(value);

         //note: supplier model should have id attribute
         supplierModel.Id = item.Key;
         query.Add(supplierModel);
        };
 }

如果不为空,则按Id过滤查询。


推荐阅读