Check if an insert or update was successful in Entity Framework

前端 未结 3 1103
眼角桃花
眼角桃花 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: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 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 UpdateEntity(Entity entityToUpdate)
    {
         if(entityToUpdate == null)
                   return false;
    
         _dataContext.Posts.Update(entityToUpdate);
    
         var updated = await _dataContext.SaveChangesAsync();
    
         return updated > 0;
    }
    

    DELETE

    public async Task 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 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

提交回复
热议问题