dotnet/efcore · error · InvalidOperationException

The property ' ' cannot be configured as…

Error message

The property '{keyProperty}' cannot be configured as 'ValueGeneratedOnUpdate' or 'ValueGeneratedOnAddOrUpdate' because it's part of a key and its value cannot be changed after the entity has been added to the store.

What it means

Thrown when a key property is configured with a ValueGenerated strategy that includes the OnUpdate flag (ValueGeneratedOnUpdate or ValueGeneratedOnAddOrUpdate). Key values must be immutable after the entity is stored, so generating a new value on update would mutate the key and break identity tracking. The Cosmos validator overrides ValidateMutableKey and rejects any such property unless it is an ordinal key property (an internal exception).

Solutions

  1. Remove the ValueGeneratedOnUpdate / ValueGeneratedOnAddOrUpdate call from the key property.
  2. If the key should be database-generated, use ValueGenerated.OnAdd (generated once at insert, never updated).
  3. Move the auto-updating behavior to a non-key property (e.g. a RowVersion or UpdatedAt).

Example fix

// before
modelBuilder.Entity<Order>()
    .Property(o => o.OrderId)
    .ValueGeneratedOnAddOrUpdate(); // OrderId is the PK

// after
modelBuilder.Entity<Order>()
    .Property(o => o.OrderId)
    .ValueGeneratedOnAdd();
Defensive patterns

Strategy: validation

Validate before calling

foreach (var et in dbContext.Model.GetEntityTypes())
{
    foreach (var key in et.GetKeys())
    {
        foreach (var p in key.Properties)
        {
            if (p.ValueGenerated.HasFlag(ValueGenerated.OnUpdate))
                throw new InvalidOperationException($"{p.Name} is a mutable key property");
        }
    }
}

Prevention

When it happens

Trigger: Calling .ValueGeneratedOnAddOrUpdate() or .ValueGeneratedOnUpdate() on a property that is part of a primary key or alternate key. Fires during key validation at model finalization.

Common situations: Slapping a generic audit-field convention (e.g. 'always regenerate on save') onto every property including keys; copy-pasting a row-version/concurrency configuration onto a key column; misusing the ValueGenerated API to mimic a database default.

Related errors


AI-assisted analysis of dotnet/efcore@3a2006ef56 (2026-08-11). Data as JSON: /api/errors/5e571b2e11d0712d. Report an issue: GitHub.

Appendix: source

Thrown at src/EFCore.Cosmos/Infrastructure/Internal/CosmosModelValidator.cs:500

                }
            }
        }
    }

    /// <summary>
    ///     Validates that a key doesn't have mutable properties.
    /// </summary>
    /// <param name="key">The key to validate.</param>
    /// <param name="logger">The logger to use.</param>
    protected override void ValidateMutableKey(
        IKey key,
        IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
    {
        var mutableProperty = key.Properties.FirstOrDefault(p => p.ValueGenerated.HasFlag(ValueGenerated.OnUpdate));
        if (mutableProperty != null
            && !mutableProperty.IsOrdinalKeyProperty())
        {
            throw new InvalidOperationException(CoreStrings.MutableKeyProperty(mutableProperty.Name));
        }
    }

    /// <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>
    protected virtual void ValidateDatabaseProperties(
        IEntityType entityType,
        IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
    {
        var properties = new Dictionary<string, IPropertyBase>();
        foreach (var property in entityType.GetProperties().Where(x => x.IsPersisted()))
        {
            var jsonName = property.GetJsonPropertyName();

View on GitHub (pinned to 3a2006ef56)