Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an insert or update was successful in Entity Framework

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/library/system.data.sqlclient.sqlcommand.executenonquery.aspx)

In EF v1, context.SaveChanges() method returns "The number of objects in an Added, Modified, or Deleted state when SaveChanges was called." (http://msdn.microsoft.com/en-us/library/bb739065.aspx)

Please tell, when multiple entities (or single entity) are added or updated to context and context.SaveChanges() method is called, how to check if actual INSERT or UPDATE was successful.

Can we assume if there was NO exception that INSERT(s) or UPDATE(s) was successful ?

Thank You

like image 200
dev Avatar asked Aug 25 '09 21:08

dev


2 Answers

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

like image 77
Andrew Peters Avatar answered Oct 18 '22 06:10

Andrew Peters


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

like image 25
Burak Avatar answered Oct 18 '22 06:10

Burak