Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generated stable values to not imply that an entity is Added #29044

Merged
merged 1 commit into from
Sep 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/EFCore/ChangeTracking/Internal/EntityGraphAttacher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,8 @@ private bool PaintAction(
? (isGenerated ? storeGenTargetState : targetState)
: EntityState.Added, // Key can only be not-set if it is store-generated
acceptChanges: true,
forceStateWhenUnknownKey: force ? targetState : null);
forceStateWhenUnknownKey: force ? targetState : null,
fallbackState: targetState);
}

return true;
Expand Down
12 changes: 2 additions & 10 deletions src/EFCore/ChangeTracking/Internal/IValueGenerationManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public interface IValueGenerationManager
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
void Generate(InternalEntityEntry entry, bool includePrimaryKey = true);
bool Generate(InternalEntityEntry entry, bool includePrimaryKey = true);

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
Expand All @@ -39,16 +39,8 @@ public interface IValueGenerationManager
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
Task GenerateAsync(
Task<bool> GenerateAsync(
InternalEntityEntry entry,
bool includePrimaryKey = true,
CancellationToken cancellationToken = default);

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
bool MayGetTemporaryValue(IProperty property, IEntityType entityType);
}
42 changes: 30 additions & 12 deletions src/EFCore/ChangeTracking/Internal/InternalEntityEntry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,19 +146,28 @@ public void SetEntityState(
EntityState entityState,
bool acceptChanges = false,
bool modifyProperties = true,
EntityState? forceStateWhenUnknownKey = null)
EntityState? forceStateWhenUnknownKey = null,
EntityState? fallbackState = null)
{
var oldState = _stateData.EntityState;
var adding = PrepareForAdd(entityState);

entityState = PropagateToUnknownKey(oldState, entityState, adding, forceStateWhenUnknownKey);
bool adding;
Setup();

if (adding || oldState is EntityState.Detached)
if ((adding || oldState is EntityState.Detached)
&& StateManager.ValueGenerationManager.Generate(this, includePrimaryKey: adding)
&& fallbackState.HasValue)
{
StateManager.ValueGenerationManager.Generate(this, includePrimaryKey: adding);
entityState = fallbackState.Value;
Setup();
}

SetEntityState(oldState, entityState, acceptChanges, modifyProperties);

void Setup()
{
adding = PrepareForAdd(entityState);
entityState = PropagateToUnknownKey(oldState, entityState, adding, forceStateWhenUnknownKey);
}
}

/// <summary>
Expand All @@ -172,20 +181,29 @@ public async Task SetEntityStateAsync(
bool acceptChanges = false,
bool modifyProperties = true,
EntityState? forceStateWhenUnknownKey = null,
EntityState? fallbackState = null,
CancellationToken cancellationToken = default)
{
var oldState = _stateData.EntityState;
var adding = PrepareForAdd(entityState);
bool adding;
Setup();

entityState = PropagateToUnknownKey(oldState, entityState, adding, forceStateWhenUnknownKey);

if (adding || oldState is EntityState.Detached)
if ((adding || oldState is EntityState.Detached)
&& await StateManager.ValueGenerationManager
.GenerateAsync(this, includePrimaryKey: adding, cancellationToken).ConfigureAwait(false)
&& fallbackState.HasValue)
{
await StateManager.ValueGenerationManager.GenerateAsync(this, includePrimaryKey: adding, cancellationToken)
.ConfigureAwait(false);
entityState = fallbackState.Value;
Setup();
}

SetEntityState(oldState, entityState, acceptChanges, modifyProperties);

void Setup()
{
adding = PrepareForAdd(entityState);
entityState = PropagateToUnknownKey(oldState, entityState, adding, forceStateWhenUnknownKey);
}
}

private EntityState PropagateToUnknownKey(
Expand Down
47 changes: 30 additions & 17 deletions src/EFCore/ChangeTracking/Internal/ValueGenerationManager.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.Metadata.Internal;

namespace Microsoft.EntityFrameworkCore.ChangeTracking.Internal;

/// <summary>
Expand Down Expand Up @@ -65,9 +63,12 @@ public ValueGenerationManager(
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual void Generate(InternalEntityEntry entry, bool includePrimaryKey = true)
public virtual bool Generate(InternalEntityEntry entry, bool includePrimaryKey = true)
{
var entityEntry = new EntityEntry(entry);
var hasStableValues = false;
var hasNonStableValues = false;

foreach (var property in entry.EntityType.GetValueGeneratingProperties())
{
if (!entry.HasDefaultValue(property)
Expand All @@ -82,12 +83,23 @@ public virtual void Generate(InternalEntityEntry entry, bool includePrimaryKey =
var generatedValue = valueGenerator.Next(entityEntry);
var temporary = valueGenerator.GeneratesTemporaryValues;

if (valueGenerator.GeneratesStableValues)
{
hasStableValues = true;
}
else
{
hasNonStableValues = true;
}

Log(entry, property, generatedValue, temporary);

SetGeneratedValue(entry, property, generatedValue, temporary);

MarkKeyUnknown(entry, includePrimaryKey, property, valueGenerator);
}

return hasStableValues && !hasNonStableValues;
}

private void Log(InternalEntityEntry entry, IProperty property, object? generatedValue, bool temporary)
Expand All @@ -108,13 +120,14 @@ private void Log(InternalEntityEntry entry, IProperty property, object? generate
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual async Task GenerateAsync(
public virtual async Task<bool> GenerateAsync(
InternalEntityEntry entry,
bool includePrimaryKey = true,
CancellationToken cancellationToken = default)
{
var entityEntry = new EntityEntry(entry);

var hasStableValues = false;
var hasNonStableValues = false;
foreach (var property in entry.EntityType.GetValueGeneratingProperties())
{
if (!entry.HasDefaultValue(property)
Expand All @@ -125,10 +138,18 @@ public virtual async Task GenerateAsync(
}

var valueGenerator = GetValueGenerator(property);
var generatedValue = await valueGenerator.NextAsync(entityEntry, cancellationToken)
.ConfigureAwait(false);
var generatedValue = await valueGenerator.NextAsync(entityEntry, cancellationToken).ConfigureAwait(false);
var temporary = valueGenerator.GeneratesTemporaryValues;

if (valueGenerator.GeneratesStableValues)
{
hasStableValues = true;
}
else
{
hasNonStableValues = true;
}

Log(entry, property, generatedValue, temporary);

SetGeneratedValue(
Expand All @@ -139,21 +160,13 @@ public virtual async Task GenerateAsync(

MarkKeyUnknown(entry, includePrimaryKey, property, valueGenerator);
}

return hasStableValues && !hasNonStableValues;
}

private ValueGenerator GetValueGenerator(IProperty property)
=> _valueGeneratorSelector.Select(property, property.DeclaringEntityType);

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual bool MayGetTemporaryValue(IProperty property, IEntityType entityType)
=> property.RequiresValueGenerator()
&& _valueGeneratorSelector.Select(property, entityType).GeneratesTemporaryValues;

private static void SetGeneratedValue(InternalEntityEntry entry, IProperty property, object? generatedValue, bool isTemporary)
{
if (generatedValue != null)
Expand Down
38 changes: 38 additions & 0 deletions test/EFCore.Tests/ChangeTracking/ChangeTrackerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3549,6 +3549,23 @@ public void Clearing_change_tracker_resets_local_view_count()
Assert.Equal(originalCount, context.Cats.Local.Count);
}

[ConditionalFact] // Issue #26448
public void Stable_generated_values_do_not_force_Added_state()
{
using var context = new EarlyLearningCenter();

Assert.Equal(EntityState.Added, context.Add(new Stable()).State);

context.ChangeTracker.Clear();
Assert.Equal(EntityState.Modified, context.Update(new Stable()).State);

context.ChangeTracker.Clear();
Assert.Equal(EntityState.Unchanged, context.Attach(new Stable()).State);

context.ChangeTracker.Clear();
Assert.Equal(EntityState.Deleted, context.Remove(new Stable()).State);
}

private static void AssertValuesSaved(int id, int someInt, string? someString)
{
using var context = new TheShadows();
Expand Down Expand Up @@ -3749,6 +3766,23 @@ public class Buggy
public int Id { get; set; }
}

private class Stable
{
public Guid Id { get; set; }
}

private class TenantIdGenerator : ValueGenerator<Guid>
{
public override Guid Next(EntityEntry entry)
=> Guid.Parse("98D06A82-C691-4988-EA39-08D98E2C8D8F");

public override bool GeneratesTemporaryValues
=> false;

public override bool GeneratesStableValues
=> true;
}

private class EarlyLearningCenter : DbContext
{
private readonly IInterceptor[] _interceptors;
Expand Down Expand Up @@ -3856,6 +3890,10 @@ protected internal override void OnModelCreating(ModelBuilder modelBuilder)
.HasForeignKey<Buggy>("BobbyId")
.OnDelete(DeleteBehavior.Cascade);
});

modelBuilder.Entity<Stable>()
.Property(e => e.Id)
.HasValueGenerator<TenantIdGenerator>();
}

private class DummyValueGenerator : ValueGenerator<int>
Expand Down