EF Core 6 - After Save entity state is reset before event is triggered
- Dominant language
- C#
- Stars
- 14.8k
- Forks
- 3.4k
- PR merge metrics
- PR metrics pending
Description
I have noticed that after an entity is saved, the SavedChanges does not have a way to see if the entity was added or updated.
The following should be a condensed version of the code I am running that shows the issue.
```C#
public class Order
{
public int id;
public float totalPrice { get; set; };
public IList _orderItems = new List();
}
public class OrderItem
{
public int id;
public float price { get; set; };
}
public sealed class OrderItemEntityInterceptor : SaveChangesInterceptor
{
public override ValueTask> SavingChangesAsync(DbContextEventData eventData,
InterceptionResult result,
CancellationToken cancellationToken = new CancellationToken())
{
if (eventData.Context is not null) {
foreach (var entityEntry in eventData.Context.ChangeTracker.Entries()) {
Console.WriteLine(entityEntry.State);
}
}
return base.SavingChangesAsync(eventData, result, cancellationToken);
}
public override ValueTask SavedChangesAsync(SaveChangesCompletedEventData eventData, int result,
CancellationToken cancellationToken = new CancellationToken())
{
if (eventData.Context is not null) {
foreach (var entityEntry in eventData.Context.ChangeTracker.Entries()) {
Console.WriteLine(entityEntry.State);
}
}
return base.SavedChangesAsync(eventData, result, cancellationToken);
}
}
```
```C#
in main:
Context.AddInterceptors(new OrderItemEntityInterceptor());
var order = await Context.Orders.FirstOrDefaultAsync(o => o.Id == orderId); // So the order is tracked by the context
order._orderItems.Add(new OrderItem {
price = 2,
})
Context.SaveChangesAsync();
```
The output for the `SavingChangesAsync` method in the interceptor is `4` which corresponds to `The entity is being tracked by the context but does not yet exist in the database.`
But the output for the `SavedChangesAsync` method is `1`, which corresponds to `The entity is being tracked by the context and exists in the database. Its property values have not changed from the values in the database.`.
I need to know if the OrderItem was Created or Updated in the last save, so I can take appropriate action (in my case a stock change and audit entry), but there is NO way to know what action was taken, as the entity's state is reset BEFORE the interceptor. You know the entity was saved, but not for what reason.
### Include provider and version information
EF Core version: 6.0.25
Database provider: Azure SQL Database 12.0
Target framework: .NET 6.0
Operating system: N/A
IDE: N/A
Contributor guide
Assessment
This issue has not been assessed yet.