Check if an insert or update was successful in Entity Framework
Yes, if there is no exception you may assume that the statements executed successfully.
Maybe this is not direct answer to the question, but may help. By default all commands are encapsulated in one DbTransaction when SaveChanges method is called (Julia Lerman, Programming Entity Framework). So, or all commands will be successfully executed, or neither. That's one way to know if insert, or update or delete was successful.
In EntityFramework, SaveChangesAsync()
returns an int.
So you can check if it is > 0
or not.
If something happens with SaveChangesAsync()
it will return the number of effected rows and this means if value > 0
then true. So simply, you can have below scenerio:
INSERT
public Task<bool> CreateEntity(Entity entity){
if(entity == null)
return false;
await _dataContext.Entities.AddAsync(entity);
var created = await _dataContext.SaveChangesAsync();
return created > 0;
}
UPDATE
public async Task<bool> UpdateEntity(Entity entityToUpdate)
{
if(entityToUpdate == null)
return false;
_dataContext.Posts.Update(entityToUpdate);
var updated = await _dataContext.SaveChangesAsync();
return updated > 0;
}
DELETE
public async Task<bool> DeleteEntity(int entityId)
{
var entity = await _dataContext.Entities.FindAsync(entityId);
if (entity == null)
return false;
_dataContext.Entities.Remove(entity);
var deleted = await _dataContext.SaveChangesAsync();
return deleted > 0;
}
And in your methods, now you can simply check if that change is success or not:
For a simple MVC scenerio:
public Task<IActionResult> CreateEntity(EntityModel model)
{
if(model == null)
return StatusCode(404);
var entity = new Entity
{
attribute1 = model.attribute1,
attribute2 = model.attribute3
};
var isCreated = await _entityService.CreateEntity(entity);
if(isCreated)
{
//do something and return a view.
}
else
{
//you can return a status code, or an error view.
}
}
You can do the same practice for Update & Delete