I’m using Blazor, with Entity Framework 7 to CRUD entities with a code first approach. I have a Position entity as follows
[Index(nameof(Barcode), IsUnique = true)]
public class Position : BaseNameEntity, IMapFrom<PositionDto>
{
/// <summary>
/// Gets or sets the position bar code.
/// </summary>
[MaxLength(64)]
public string Barcode { get; set; }
. . .
I have a generic Repository with an Add method as follows
public virtual async Task<int> Add(TDto dto)
{
var entity = _mapper.Map<TEntity>(dto);
SetNavigationPropertiesToNull(entity);
_db.Set<TEntity>().Add(entity);
await _db.SaveChangesAsync();
return entity.Id;
}
My Database Context is built as follows in program.cs
builder.Services.AddDbContext<DataContext>(options =>
options.UseSqlServer(dbSettings.DataContextConnection, b =>
{
b.MigrationsAssembly("redacted");
}).EnableSensitiveDataLogging(), ServiceLifetime.Transient);
As you can see, I am using a Unique index on the Position Barcode property. In my UI, If I try to add a new Position with an existing Barcode, in this example ‘aa’ just for a quick test, I get an expected error as there is already a Position with Barcode ‘aa’ in the database.
An error occurred while saving the entity changes. See the inner exception for details. Cannot insert duplicate key row in object 'dbo.Positions' with unique index 'IX_Positions_Barcode'. The duplicate key value is (aa).
I then edit the UI to change the Barcode to something new, say ‘bbbb1234’ and re-sumbit. In debug, I check the dto and it correctly shows the Barcode as ‘bbbb1234’. The entity gets mapped with the new Barcode as expected. However upon await _db.SaveChangesAsync(), I get the same error again. It’s as if my context has saved the ‘aa’ addition even though it threw an exception previously
An error occurred while saving the entity changes. See the inner exception for details. Cannot insert duplicate key row in object 'dbo.Positions' with unique index 'IX_Positions_Barcode'. The duplicate key value is (aa).
Can anyone help me? Do I need to somehow clear my context of any erroneous additions?
Any advice appreciated.