Batch Editing SaveChanges Erorr
Hello.
I am encountering the following error:
"The instance of entity type 'Product' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached."
This error occurs after I make changes in a table in EditMode.Batch and execute _dbContext.SaveChanges().
However, if I edit the data without using the table, through code, the error does not occur and everything works correctly.
Please help me resolve this issue.
@inject ApplicationDbContext _dbContext;
@*
editors for Supply fields
...
...
...
*@
<SfGrid @ref="SupplyProductsGrid"
DataSource="@Supply!.SupplyProducts"
Toolbar="@(new List<string>() { "Add", "Delete" })"
AllowPaging="true"
AllowSorting="true"
AllowResizing="true"
EnableHover="true"
TextWrapSettings="@(new GridTextWrapSettings(){ WrapMode = WrapMode.Content})">
<GridEditSettings AllowAdding="true"
AllowDeleting="true"
AllowEditing="true"
ShowConfirmDialog="false"
Mode="EditMode.Batch" />
<GridEvents TValue="SupplyProduct" CellSaved="@(() => SupplyProductsGrid.EndEditAsync())" />
<GridPageSettings PageSize="20" PageSizes="true" PageCount="10" />
<GridColumns>
<GridColumn Field="Id" IsPrimaryKey="true" Visible="false" AllowEditing="false" />
<GridColumn Field="Product.Id" Width="75" AllowEditing="false" />
<GridColumn Field="Product.Sku" Width="130" AllowEditing="false" />
<GridColumn Field="Product.Name" AllowEditing="false" />
<GridColumn Field="Product.Unit.Name" Width="100" AllowEditing="false" />
<GridColumn Field="Quantity" HeaderText="Количество" Width="100" />
<GridColumn Field="Price" HeaderText="Цена" Width="100" />
</GridColumns>
</SfGrid>
<SfButton OnClick="Save">Save</SfButton>
@code {
private SfGrid<SupplyProduct> SupplyProductsGrid { get; set; } = null!;
private Supply? Supply = new();
protected override async Task OnInitializedAsync()
{
Supply = await _dbContext.Supplies
.Include(i => i.SupplyProducts)
.ThenInclude(i => i.Product)
.ThenInclude(i => i.Unit)
.FirstOrDefaultAsync(i => i.Id == 3);
}
private async Task Save()
{
await _dbContext.SaveChangesAsync();
}
}
public class Supply
{
public int Id { get; set; }
...
...
public virtual ICollection<Supply Product> SupplyProducts { get; set; } = new List<SupplyProduct>();
}
public class SupplyProduct
{
public int Id { get; set; }
public int SupplyId { get; set; }
public int ProductId { get; set; }
...
...
public float Quantity { get; set; }
public decimal? Price { get; set; }
public virtual Product Product { get; set; } = null!;
public virtual Supply Supply { get; set; } = null!;
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
...
...
public int? UnitId { get; set; }
public virtual ProductUnit? Unit { get; set; }
}
public class ProductUnit
{
public int Id { get; set; }
public string Name { get; set; } = null!;
}
Hi Pavel Rembrant,
Based on the reported issue, it appears that the error you are encountering is
commonly related to Entity Framework Core and occurs when multiple instances of
the same entity with identical primary keys are being tracked simultaneously.
However, we attempted to reproduce the issue on our end but were unable to
replicate it. To proceed further with the investigation, we kindly request
additional information from your side. Please provide the following details:
- To analyze the reported issue, could you please share a simple and reproducible sample that demonstrates the problem? This will assist us in identifying the issue more efficiently and providing a resolution.
- Kindly share your attempt to replicate the issue using the attached simple sample.
Above-requested details will be very helpful in validating the reported query at our end and providing a solution as early as possible. Thanks for your understanding.
Additionally
reference.
https://blazor.syncfusion.com/documentation/datagrid/data-binding#sql-server-data-bindingsql-client
Regards,
Prathap Senthil
Attachment: BlazorDataGridSQLNet8_b61bb619.zip
-
Set the
ConnectionString. -
Apply the migration.
-
Run the application and open the
Index.razorpage. -
Enter any new value in the
QuantityorPricecolumn in any row. -
Click the Save button.
The data was not saved. You can see the error in the browser console.
Hello, thank you for your response.
I’ve attached a sample application with the error.
Steps to reproduce the issue:
Attachment: ErrorExample_543c3ab1.zip
Based on the reported problem, this issue occurs when you call SaveChangesAsync() but Entity Framework is already tracking an entity with the same Id. This can happen in common Blazor patterns for example, if you retrieve a Product from the database and later attempt to re-attach or update a second instance of the same Product with the same Id.
To
resolve this issue, note that you have set the primary column’s Visible
property to false, which causes the same key to be added repeatedly—leading to
the problem you’re experiencing. We suggest setting the IsIdentity property on
the primary column to avoid duplicate keys. If the primary key column is
auto-incremented in your database, please ensure that the IsIdentity property
of the GridColumn is set to true for the primary key column. When IsIdentity is
enabled, the column will be treated as read-only during editing or when adding
a new record. Please refer to the documentation provided for more details.
Note: If you wish to hide the primary key column, ensure that the IsIdentity
property is enabled in the grid column and also correctly configured in the
database. Refer to the documentation for additional guidance.
Additionally, in the previous update, we included a sample with proper CRUD
operations that update the database. Based on that, you will need to handle the
CRUD operations on your end.
General reference :
https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud?view=aspnetcore-9.0
https://learn.microsoft.com/en-us/ef/core/saving/disconnected-entities#resolving-the-instance-of-entity-type-cannot-be-tracked-error
- 3 Replies
- 2 Participants
-
PR Pavel Rembrant
- Apr 9, 2025 07:36 AM UTC
- Apr 14, 2025 03:20 PM UTC