My code looks like this:
public async Task<IHttpActionResult> Delete(int id)
{
var userId = Int32.Parse(User.Identity.GetUserId());
UserTest userTest = await db.UserTests.FindAsync(id);
if (userTest == null)
{
return NotFound();
}
if (userTest.UserId != userId)
{
return Unauthorized();
}
db.UserTests.Remove(userTest);
await db.SaveChangesAsync();
return Ok();
}
I think everything up to the db.SaveChangesAsync is okay but how can I confirm if the db.SaveChangesAsync works before doing a return Ok() ? Ideally I think I should be checking for exceptions and things but I am not sure how I could fit that into this code block.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
From msdn:
public virtual Task<int> SaveChangesAsync()
Return Value Type: System.Threading.Tasks.Task A task that
represents the asynchronous save operation. The task result contains
the number of objects written to the underlying database.
Check if the result is greater than 0:
if(await db.SaveChangesAsync() > 0)
{
.....
}
Another option is to wrap this with try ... catch block:
try
{
await db.SaveChangesAsync();
return Ok();
}
catch (Exception ex)
{
return NotFound(ex.Message);
}
Method 2
You can use the following below 🙂
try {
int writtenEntriesCount = await db.SaveChangesAsync();
if(writtenEntriesCount > 0){
// is saved
}else{
// is not saved
}
} catch(e) {
// handle error here
}
Method 3
I normally use this if it helps:
try
{
_context.Events.Add(entity);
await _context.SaveChangesAsync(cancellationToken);
return new CommandResult() { IsSuccess = true };
}
catch (Exception ex)
{
return new CommandResult() { IsSuccess = false,IsError =True, Message=ex.Message };
}
public class CommandResult
{
public bool IsSuccess { get; internal set; }
public bool IsError { get; internal set; }
public string Message { get; internal set; }
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0