I have a DTO:
public class UserDTO
{
public int uid {get;set;}
public string name {get;set;}
}
// example of what the udto gets as a request from the front-end
var theList = new List<UserDTO>()
{
new UserDTO { uid = 1, name = "Bob Smith" },
new UserDTO { uid = 2, name = "Jane Jones" },
};
In the DB: Bob's exists with a status of 0 and Janes does not exist in the DB. So the loop checks to see if the user exists with a status of 0, if so, then updates the DB status from 0 to 1 with _myCtx.Update(). Then once updated, it removes Bob's object because I dont want to duplicate Bob as he exists already, I need Bobs object removed and then move on to the next loop where it adds Jane into the DB.
public async Task<IActionResult> AddUser([FromBody] List<UserDTO> udto)
{
var toRemove = new HashSet<UserDTO>();
foreach(var item in udto)
{
var userFalse = await _myCtx.Users.SingleOrDefaultAsync(o => o.uid == item.uid && o.status == 0);
if(userFalse != null) // if user found, I want to update
{
item.Status = 1;
_myCtx.Users.Update(userFalse);
await _myCtx.SaveChanges(); //save into the DB the status to 1
if(item.uid == userFalse.uid){ toRemove.Add(item); } //need Bob removed here
} // below I want to add if they don't exist
udto.RemoveAll(toRemove.Contains);
item.name = udto.name;
var myEntity = _mapper.Map(item);
await _myCtx.Users.AddAsync(myEntity);
// Jane gets added, but so does Bob as a duplicate
}
await _myCtx.SaveChangesAsync();
return Ok("User Added");
}
The item is removed AFTER the loop is done and the reason its adding it to the DB. Is there a way to remove Bob before it continues after or inside the if clause so it does not get added to the DB? Thank you all.