Skip to content

PropertyValues.SetValues(obj) causes DELETE instead of UPDATE #16546

Closed

Description

@aureole82

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

modelBuilder.Entity<ContainerRoom>()
    .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):

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

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

Activity

  1. ajcvickers commented on Jul 10, 2019

    @ajcvickers
    Contributor

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

  2. ajcvickers commented on Jul 15, 2019

    @ajcvickers
    Contributor

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

  3. self-assigned this
    on Jul 19, 2019
  4. added this to the Backlog milestone on Jul 19, 2019
  5. modified the milestones: Backlog, 5.0.0 on Nov 13, 2019
  6. 9 remaining items

  7. modified the milestones: 3.1.x, 3.1.3 on Feb 15, 2020
  8. removed their assignment
    on Sep 1, 2024
  9. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions