【问题标题】:c# Firesharp - How to update a single value of an object?c# Firesharp - 如何更新对象的单个值?
【发布时间】:2021-01-26 04:00:51
【问题描述】:

我有一个 c# 项目,我正在尝试使用 FireSharp 更新对象的单个值。但是,当我这样做时,它会删除其他字符串对象。

tldr 问题:

是否可以使用 Firesharp 仅更新对象的单个字段,还是在更新时必须包含所有字段?

在他们 GitHub 上的示例中,他们将所有字段设置为:

var todo = new Todo {
                name = "Execute SET",
                priority = 2
            };
SetResponse response = await _client.SetAsync("todos/set", todo);
Todo result = response.ResultAs<Todo>(); //The response will contain the data written

然后他们用 :

更新字段
var todo = new Todo {
                name = "Execute UPDATE!",
                priority = 1
            };

FirebaseResponse response =await  _client.UpdateAsync("todos/set", todo);
Todo todo = response.ResultAs<Todo>(); //The response will contain the data written

I know this is possible in other languages 所以我觉得这在 FireSharp 中应该是可能的。

我的情况:

例如,如果我有一个像 StudentProfile 这样的课程:

class StudentProfile {
   public string Firstname {get; set;}
   public string Lastname {get; set;}
   public int Age {get; set;}
}

当我上传到 firebase 时,我使用:

StudentProfile studentProfile = new StudentProfile 
{
   Firstname = "John",
   Lastname = "Doe",
   Age = 18
};

client.Set("Students/" + firebaseUserId + "/StudentProfile", studentProfile);

现在假设我想更新年龄。首先我会得到信息:

var result = client.Get("Students/" + firebaseUserId + "/StudentProfile");

StudentProfile student = result.ResultAs<StudentProfile>();

现在我只想更新年龄。但是,这似乎是更新 Age 的地方,但随后删除了其他字符串值

int newAge = student.Age + 1;

StudentProfile updatedStudent = new StudentProfile 
{
   Age = newAge
};

client.UpdateAsync("Students/" + firebaseUserId + "/StudentProfile, updatedStudent)

是否可以使用 Firesharp 仅更新对象的单个字段,还是在更新时必须包含所有字段?

基本上,如果我每次想要更新某些内容时都必须始终如一地写出所有字段,那会很痛苦。

【问题讨论】:

标签: c# firebase firebase-realtime-database fire-sharp


【解决方案1】:

最简单的方法就是把左边的路径展开到年龄,然后使用SetAsync

client.GetAsync(
  "Students/" + firebaseUserId + "/StudentProfile/Age", 
  newAge
)

【讨论】:

    【解决方案2】:

    您可以将要更新的值存储为Dictionary&lt;string,object&gt;。然后你甚至可以通过将路径定义为字符串来更新和推送嵌套对象。

    你的例子:

    int newAge = student.Age + 1;
    
    Dictionary<string,object> updatedStudent = new Dictionary<string,object>(); 
    updatedStudent.Add("Age",newAge);
    
    client.UpdateAsync("Students/" + firebaseUserId + "/StudentProfile, updatedStudent);
    

    添加这样的东西,会将嵌套对象推送到 jsontree:

        ...
    updatedStudent.Add("Address/Street","Main Ave. 1");
    client.UpdateAsync("Students/" + firebaseUserId + "/StudentProfile, updatedStudent);
    

    结果是:

        {
           "Firstname": "John",
           "Lastname": "Doe",
           "Age": 18,
           "Address":{
               "Street": "Main Ave. 1"
           }
    
        }
    

    【讨论】:

      猜你喜欢
      • 2022-11-15
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 2017-11-08
      • 2021-07-17
      • 1970-01-01
      相关资源
      最近更新 更多