Efcore: PropertyValues.SetValues(obj) causes DELETE instead of UPDATE

Created on 10 Jul 2019  路  5Comments  路  Source: dotnet/efcore

Describe what is not working as expected.
DELETE FROM [ContainerRooms] WHERE [Id] = ...;
instead of
UPDATE [ContainerRooms] SET [ProductId] = NULL WHERE [Id] = ...;

Steps to reproduce

Eval.EFCore.DeleteInsteadUpdate.zip

Schema:
Container 1-n ContainerRoom n-1 Product
```c#
modelBuilder.Entity()
.HasOne(room => room.Product)
.WithMany(product => product.Rooms)
.HasForeignKey(room => room.ProductId)
.IsRequired(false)
.OnDelete(DeleteBehavior.Cascade)
;

Assume the following use case (where the room will be emptied):
```c#
var detachedRoom = detachedContainer.Rooms.First();
// Prepare update (remove product from room).
detachedRoom.Product = null;
detachedRoom.ProductId = null;

var attachedRoom = attachedContainer.Rooms.Single();
Console.WriteLine($"Before update: {db.Entry(attachedRoom).State}"); // Unchanged
// Update.
//attachedRoom.ProductId = null;
//attachedRoom.Product = null;
db.Entry(attachedRoom).CurrentValues.SetValues(detachedRoom);

Console.WriteLine($"After update: {db.Entry(attachedRoom).State}"); // Modified
await db.SaveChangesAsync(); // DELETE FROM [ContainerRooms] WHERE [Id] = @p0; ???
Console.WriteLine($"After persist: {db.Entry(attachedRoom).State}"); // Detached :-(

Instead of updating the ContainerRoom it will be deleted!

Workaround

c# attachedRoom.ProductId = null; attachedRoom.Product = null; await db.SaveChangesAsync(); // UPDATE [ContainerRooms] SET [ProductId] = @p0 WHERE [Id] = @p1;

Further technical details

EF Core version: 2.2.6
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10
IDE: Visual Studio 2019, Version 16.1.6

Servicing-approved closed-fixed customer-reported type-bug

Most helpful comment

Consider to patch 3.1, please!
Otherwise the complete _Long Term Support_ promise makes no sense to me.

All 5 comments

Note for triage: I was able to reproduce this. Will require some more investigation to figure out what is going wrong.

Note for triage: confirmed that this still repros in 3.0.

In which version is this fixed? Will the fix be published in Version 3.1?

@aureole82 The milestone on the issue indicates which release this is targeted for--currently 5.0. We may choose to patch 3.1 with this, but that's not currently the plan.

Consider to patch 3.1, please!
Otherwise the complete _Long Term Support_ promise makes no sense to me.

Was this page helpful?
0 / 5 - 0 ratings