Entity with error not removed from context

An error raised by the database in an operation to add a record is not removing the record from context after the SaveChanges failed. If the user cancels the dialog and tries to add another record, the wrong entity will still be inserted in the context and SaveChances will show an error again.

A suggestion:

On DataBaseService class

partial void OnCancelCreateAsync(TbEntity item);

public async Task<TbEntity> CancelCreateAsync(TbEntity item)
{
    var entity = _dbContext.Entry(item);
    if (entity.State != EntityState.Detached)
        _dbContext.TbEntity.Remove(item);
    return item;
}

On AddEntity.razor.designer.cs class

Cancel Button

protected async System.Threading.Task.Task Button2Click(MouseEventArgs args)
{
    await DataBaseService.CancelCreateAsync(tbentity);
    DialogService.Close(null);
}

Hi @licitec,

I'm unable to reproduce such problem. I've started and canceled Add dialog and after that I was able to add records normally.

To reproduce the error, add a record that will duplicate an index in the database (name, for example). The system will return an index duplication error. In the next step, cancel the dialog to return to the grid. Now add a record without the duplicate index problem. The errored entity (added to the context in the previous command) will still be in context and SaveChanges will return failure.

I hope the Portuguese to English translation is intelligible.

1 Like