Skip to content

Allow explicit temporary values that are stored in the entity instance #24245

Closed

Description

While an application is free to manipulate and set temporary values, those values will never be reflected in the entity instance since the current code requires a CLR default value in the entity instance before it will consider a value temporary. This makes it difficult to work with explicit temporary values outside the context of EF Core where the values need to be set into the entities even after EF Core is tracking them.


Originally reported by @Zero3 here: #12378 (comment)

you are free to set the temporary value into the entity if you want it there

I tried this, but as mentioned above, EF will then save the temporary value to database. And if one manually does context.Entry(entity).Property(e => e.Id).IsTemporary = true;, then EF resets Id back to 0, and we are back where we started.

Here is an example of a custom .Add() method that doesn't work because of this behaviour:

public EntityEntry<EntityBase> AddWithTemporaryId(EntityBase entity)
{
	EntityEntry<EntityBase> entityEntry = base.Add(entity);

	Console.WriteLine("Initial entity value: " + entity.Id);
	Console.WriteLine("Is value temporary: " + entityEntry.Property(e => e.Id).IsTemporary);
	Console.WriteLine("EF temporary value: " + entityEntry.Property(e => e.Id).CurrentValue);
	
	Console.WriteLine("Setting entity value to temporary value");
	entity.Id = entityEntry.Property(e => e.Id).CurrentValue;
	
	Console.WriteLine("Entity value: " + entity.Id);
	Console.WriteLine("Is value temporary: " + entityEntry.Property(e => e.Id).IsTemporary);
	
	Console.WriteLine("Marking entity value as temporary");
	entityEntry.Property(e => e.Id).IsTemporary = true;
	
	Console.WriteLine("Is value temporary: " + entityEntry.Property(e => e.Id).IsTemporary);
	Console.WriteLine("Entity value: " + entity.Id);
	
	return entityEntry;
}

Output:

Initial entity value: 0
Is value temporary: True
EF temporary value: -2147482647
Setting entity value to temporary value
Entity value: -2147482647
Is value temporary: False
Marking entity value as temporary
Is value temporary: True
Entity value: 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

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions