Check if an insert or update was successful in Entity Framework

前端 未结 3 1098
眼角桃花
眼角桃花 2021-01-18 05:25

In ADO.NET, ExecuteNonQuery() \"For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command\" (http://msdn.microsoft.com/en-us/

相关标签:
3条回答
  • 2021-01-18 06:06

    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.

    0 讨论(0)
  • 2021-01-18 06:07

    Yes, if there is no exception you may assume that the statements executed successfully.

    0 讨论(0)
  • 2021-01-18 06:25

    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

    0 讨论(0)
提交回复
热议问题