I'm building an API using ASP.NET Core 6 with mongodb as database. I'm trying to set a certain field to toggle from true to false and vice versa. If the field isactive:"True"
then I have to update it to false and vice versa.
I have figured out how to update the value, but I have to toggle this field to opposite value automatically without having to specify the value.
Here is the repository class:
public bool UpdateStatus(string id)
{
_activity.UpdateOne(x => x.Id == id,
Builders<Activity>.Update.Set(u => u.IsActive,false));
return true;
}
Controller for above repository:
public ActionResult putbystatus(string id)
{
var existingactivity = activityRepository.Get(id);
if (existingactivity == null)
{
return NotFound($"Activity with provider id = {id} not found");
}
activityRepository.UpdateStatus(id);
return NoContent();
}
CodePudding user response:
you can write like below
public bool UpdateStatus(string id)
{
var filter = Builders<Activity>.Filter.Eq("Id", id);
_activity.UpdateOne(filter,
Builders<Activity>.Update.Set(u => u.IsActive,!_activity.Find(filter).FirstOrDefault().IsActive));
return true;
}
//or if you can modify the repository to accept IsActive value
public bool UpdateStatus(string id, bool isActive)
{
_activity.UpdateOne(x => x.Id == id,
Builders<Activity>.Update.Set(u => u.IsActive, isActive));
return true;
}
//Controller for above repository
public ActionResult putbystatus(string id)
{
var existingactivity = activityRepository.Get(id);
if (existingactivity == null)
{
return NotFound($"Activity with provider id = {id} not found");
}
activityRepository.UpdateStatus(id,!existingactivity.IsActive);
return NoContent();
}
[enter image description here][1]
[1]: https://i.stack.imgur.com/tytAK.png