Skip to content

Set CollectionEntry.IsModified to true when removing items from a collection #24076

Open

Description

File a bug

The IsModified property on a CollectionEntry does not correctly reflect it has been modified if the action is only to remove an entry from the collection.

The intent seems to be for that field to reflect that, given in the source code there are code checks for entries with a State of Deleted and previous work done for #10450.

Include your code

This is easy to reproduce adding some additional cases to your SqlServerEndToEndTests fixture, which I've tested in my own efcore fork:

[ConditionalFact]
public void Removing_an_item_from_a_collection_marks_it_as_modified()
{
	using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
	var options = Fixture.CreateOptions(testDatabase);

	using var context = new GameDbContext(options);
	context.Database.EnsureCreatedResiliently();

	var player = new PlayerCharacter(
		new Level { Game = new Game() });

	var weapon = new Item { Id = 1, Game = player.Game };

	player.Items.Add(weapon);

	context.Characters.Add(player);

	context.SaveChanges();

	player.Items.Remove(weapon);

	context.ChangeTracker.DetectChanges();
	
	// this fails
	Assert.True(context.Entry(player).Collection(p => p.Items).IsModified);
}

⚠️ As I was testing these behaviours I noticed that attempting to delete the weapon entity after setting it as player.CurrentWeapon = weapon; would throw an exception as it seems EF tries to clear both foreign keys for CurrentWeapon in PlayerCharacter - CurrentWeaponId and GameId - however because GameId is used in other required relationships that causes an exception to be thrown. Clearing the weapon player.CurrentWeapon = null; as opposed to deleting the entity context.Remove(weapon); seems to work fine, so perhaps that's a possible bug as well?

Include stack traces

n/a

Include verbose output

n/a

Include provider and version information

Using latest released EF Core version (3.1.1) targeting .NET 5.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions