// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Data;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace Microsoft.EntityFrameworkCore.Infrastructure;
///
/// The validator that enforces rules common for all relational providers.
///
/// Parameter object containing dependencies for this service.
/// Parameter object containing relational dependencies for this service.
///
///
/// The service lifetime is . This means a single instance
/// is used by many instances. The implementation must be thread-safe.
/// This service cannot depend on services registered as .
///
///
/// See Implementation of database providers and extensions
/// for more information and examples.
///
///
public class RelationalModelValidator(
ModelValidatorDependencies dependencies,
RelationalModelValidatorDependencies relationalDependencies)
: ModelValidator(dependencies)
{
///
/// Relational provider-specific dependencies for this service.
///
protected virtual RelationalModelValidatorDependencies RelationalDependencies { get; } = relationalDependencies;
///
/// Validates a model, throwing an exception if any errors are found.
///
/// The model to validate.
/// The logger to use.
public override void Validate(IModel model, IDiagnosticsLogger logger)
{
base.Validate(model, logger);
var tables = new Dictionary>();
var views = new Dictionary>();
var storedProcedures = new Dictionary>();
foreach (var entityType in model.GetEntityTypes())
{
var tableId = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table);
if (tableId != null)
{
var table = tableId.Value;
if (!tables.TryGetValue(table, out var tableMappedTypes))
{
tableMappedTypes = [];
tables[table] = tableMappedTypes;
}
tableMappedTypes.Add(entityType);
}
var viewId = StoreObjectIdentifier.Create(entityType, StoreObjectType.View);
if (viewId != null)
{
var view = viewId.Value;
if (!views.TryGetValue(view, out var viewMappedTypes))
{
viewMappedTypes = [];
views[view] = viewMappedTypes;
}
viewMappedTypes.Add(entityType);
}
AddStoredProcedure(StoreObjectType.DeleteStoredProcedure, entityType, storedProcedures);
AddStoredProcedure(StoreObjectType.InsertStoredProcedure, entityType, storedProcedures);
AddStoredProcedure(StoreObjectType.UpdateStoredProcedure, entityType, storedProcedures);
}
foreach (var (table, mappedTypes) in tables)
{
ValidateTable(mappedTypes, table, logger);
}
foreach (var (view, mappedTypes) in views)
{
ValidateView(mappedTypes, view, logger);
}
foreach (var dbFunction in model.GetDbFunctions())
{
ValidateDbFunction(dbFunction, logger);
}
foreach (var sequence in model.GetSequences())
{
ValidateSequence(sequence, logger);
}
foreach (var (sproc, mappedTypes) in storedProcedures)
{
ValidateStoredProcedure(mappedTypes, sproc, logger);
}
static void AddStoredProcedure(
StoreObjectType storedProcedureType,
IEntityType entityType,
Dictionary> storedProcedures)
{
var sprocId = StoreObjectIdentifier.Create(entityType, storedProcedureType);
if (sprocId == null)
{
return;
}
if (!storedProcedures.TryGetValue(sprocId.Value, out var mappedTypes))
{
mappedTypes = [];
storedProcedures[sprocId.Value] = mappedTypes;
}
mappedTypes.Add(entityType);
}
}
///
protected override void ValidateEntityType(
IEntityType entityType,
IDiagnosticsLogger logger)
{
base.ValidateEntityType(entityType, logger);
ValidateMappingFragment(entityType, logger);
ValidateSqlQuery(entityType, logger);
ValidateDbFunctionMapping(entityType, logger);
ValidateStoredProcedures(entityType, logger);
ValidateContainerColumnType(entityType, logger);
ValidateTphTriggers(entityType, logger);
ValidateOwnedEntityMappedToJsonCollection(entityType, logger);
// TODO: support this for raw SQL and function mappings in #19970 and #21627 and remove the check
ValidateJsonEntityOwnerMappedToTableOrView(entityType, logger);
}
///
/// Logs a warning if an owned entity type is mapped to JSON as a collection, which uses a synthesized ordinal key. This mapping
/// is obsolete; the type should be mapped as a complex type collection instead.
///
/// The entity type to validate.
/// The logger to use.
protected virtual void ValidateOwnedEntityMappedToJsonCollection(
IEntityType entityType,
IDiagnosticsLogger logger)
{
if (entityType.IsMappedToJson()
&& entityType.FindPrimaryKey() is { } primaryKey
&& primaryKey.Properties.Any(p => p.IsOrdinalKeyProperty()))
{
logger.OwnedEntityMappedToJsonCollectionWarning(entityType);
}
}
///
/// Logs a warning if triggers are defined on a non-root entity type using TPH mapping strategy.
///
/// The entity type to validate.
/// The logger to use.
protected virtual void ValidateTphTriggers(
IEntityType entityType,
IDiagnosticsLogger logger)
{
if (entityType.GetDeclaredTriggers().Any()
&& entityType.BaseType is not null
&& entityType.GetMappingStrategy() == RelationalAnnotationNames.TphMappingStrategy)
{
logger.TriggerOnNonRootTphEntity(entityType);
}
}
///
protected override void ValidateProperty(
IProperty property,
ITypeBase structuralType,
IDiagnosticsLogger logger)
{
base.ValidateProperty(property, structuralType, logger);
if (RelationalPropertyOverrides.Get(property) is { } storeObjectOverrides)
{
foreach (var storeObjectOverride in storeObjectOverrides)
{
ValidatePropertyOverride(property, storeObjectOverride, logger);
}
}
ValidateBoolWithDefaults(property, logger);
}
///
protected override void ValidateAutoLoaded(
IProperty property,
ITypeBase structuralType,
IDiagnosticsLogger logger)
{
base.ValidateAutoLoaded(property, structuralType, logger);
if (!property.IsAutoLoaded
&& structuralType.IsMappedToJson())
{
throw new InvalidOperationException(
RelationalStrings.AutoLoadedJsonProperty(property.Name, structuralType.DisplayName()));
}
}
///
protected override void ValidateKey(
IKey key,
IDiagnosticsLogger logger)
{
base.ValidateKey(key, logger);
foreach (var property in key.Properties)
{
if (property.DeclaringType is IComplexType complexType
&& complexType.IsMappedToJson())
{
throw new InvalidOperationException(
RelationalStrings.KeyPropertyInJsonComplexType(
key.Properties.Format(),
key.DeclaringEntityType.DisplayName(),
property.Name));
}
}
ValidateDefaultValuesOnKey(key, logger);
ValidateValueGeneration(key, logger);
}
///
/// Validates a primitive collection property.
///
/// The property to validate.
/// The logger to use.
protected override void ValidatePrimitiveCollection(
IProperty property,
IDiagnosticsLogger logger)
{
base.ValidatePrimitiveCollection(property, logger);
if (property is { IsPrimitiveCollection: true }
&& property.GetTypeMapping().ElementTypeMapping?.ElementTypeMapping != null)
{
throw new InvalidOperationException(
RelationalStrings.NestedCollectionsNotSupported(
property.ClrType.ShortDisplayName(), property.DeclaringType.DisplayName(), property.Name));
}
}
///
protected override void ValidatePropertyMapping(
IComplexProperty complexProperty,
IDiagnosticsLogger logger)
{
base.ValidatePropertyMapping(complexProperty, logger);
if (complexProperty.IsCollection && !complexProperty.ComplexType.IsMappedToJson())
{
throw new InvalidOperationException(
RelationalStrings.ComplexCollectionNotMappedToJson(
complexProperty.DeclaringType.DisplayName(), complexProperty.Name));
}
// Only owned collections with synthetic keys are deprecated, see ValidateOwnedEntityMappedToJsonCollection
// TODO: Implement, see Issue 39692
if (complexProperty.DeclaringType is IEntityType declaringEntityType
&& declaringEntityType.IsMappedToJson()
&& IsInJsonOwnedCollection(declaringEntityType))
{
throw new InvalidOperationException(
RelationalStrings.ComplexPropertyInJsonOwnedCollection(
$"{declaringEntityType.DisplayName()}.{complexProperty.Name}", declaringEntityType.DisplayName()));
}
if (!complexProperty.ComplexType.IsMappedToJson()
&& complexProperty.IsNullable
&& complexProperty.ComplexType.GetProperties().All(m => m.IsNullable))
{
throw new InvalidOperationException(
RelationalStrings.ComplexPropertyOptionalTableSharing(complexProperty.ComplexType.DisplayName(), complexProperty.Name));
}
if (complexProperty.GetJsonPropertyName() != null
&& ((IConventionAnnotation?)complexProperty.ComplexType.FindAnnotation(RelationalAnnotationNames.JsonPropertyName))
?.GetConfigurationSource() != ConfigurationSource.DataAnnotation)
{
if (complexProperty.ComplexType.FindAnnotation(RelationalAnnotationNames.ContainerColumnName)?.Value is string)
{
throw new InvalidOperationException(
RelationalStrings.ComplexPropertyBothJsonColumnAndJsonPropertyName(
$"{complexProperty.DeclaringType.DisplayName()}.{complexProperty.Name}",
complexProperty.ComplexType.GetContainerColumnName(),
complexProperty.GetJsonPropertyName()));
}
if (!complexProperty.DeclaringType.IsMappedToJson())
{
throw new InvalidOperationException(
RelationalStrings.ComplexPropertyJsonPropertyNameWithoutJsonMapping(
$"{complexProperty.DeclaringType.DisplayName()}.{complexProperty.Name}"));
}
}
if (complexProperty.ComplexType.FindAnnotation(RelationalAnnotationNames.ContainerColumnName)?.Value is string
&& complexProperty.DeclaringType.IsMappedToJson())
{
throw new InvalidOperationException(
RelationalStrings.NestedComplexPropertyJsonColumn(
$"{complexProperty.DeclaringType.DisplayName()}.{complexProperty.Name}",
complexProperty.ComplexType.GetContainerColumnName(),
complexProperty.DeclaringType.DisplayName(),
complexProperty.DeclaringType.GetContainerColumnName()));
}
if (complexProperty.ComplexType.IsMappedToJson())
{
if (!complexProperty.DeclaringType.IsMappedToJson()
&& complexProperty.DeclaringType is IComplexType)
{
// Issue #36558
throw new InvalidOperationException(
RelationalStrings.NestedComplexPropertyJsonWithTableSharing(
$"{complexProperty.DeclaringType.DisplayName()}.{complexProperty.Name}",
complexProperty.DeclaringType.DisplayName()));
}
ValidateJsonProperties(complexProperty.ComplexType);
}
return;
static bool IsInJsonOwnedCollection(IEntityType entityType)
{
while (entityType.IsMappedToJson()
&& entityType.FindOwnership() is { } ownership)
{
if (!ownership.IsUnique)
{
return true;
}
entityType = ownership.PrincipalEntityType;
}
return false;
}
}
///
/// Validates the SQL query mapping for an entity type.
///
/// The entity type to validate.
/// The logger to use.
protected virtual void ValidateSqlQuery(
IEntityType entityType,
IDiagnosticsLogger logger)
{
var sqlQuery = entityType.GetSqlQuery();
if (sqlQuery == null)
{
return;
}
if (entityType.BaseType != null
&& (entityType.FindDiscriminatorProperty() == null
|| sqlQuery != entityType.BaseType.GetSqlQuery()))
{
throw new InvalidOperationException(
RelationalStrings.InvalidMappedSqlQueryDerivedType(
entityType.DisplayName(), entityType.BaseType.DisplayName()));
}
}
///
/// Validates a single sequence.
///
/// The sequence to validate.
/// The logger to use.
protected virtual void ValidateSequence(
ISequence sequence,
IDiagnosticsLogger logger)
{
}
///
/// Validates a single database function.
///
/// The database function to validate.
/// The logger to use.
protected virtual void ValidateDbFunction(
IDbFunction dbFunction,
IDiagnosticsLogger logger)
{
var model = dbFunction.Model;
if (dbFunction.IsScalar)
{
if (dbFunction.TypeMapping == null)
{
throw new InvalidOperationException(
RelationalStrings.DbFunctionInvalidReturnType(
dbFunction.ModelName,
dbFunction.ReturnType.ShortDisplayName()));
}
}
else
{
var elementType = dbFunction.ReturnType.GetGenericArguments()[0];
var entityType = model.FindEntityType(elementType);
if (entityType?.IsOwned() == true
|| ((IConventionModel)model).IsOwned(elementType)
|| (entityType == null && model.GetEntityTypes().Any(e => e.ClrType == elementType)))
{
throw new InvalidOperationException(
RelationalStrings.DbFunctionInvalidIQueryableOwnedReturnType(
dbFunction.ModelName, elementType.ShortDisplayName()));
}
if (entityType == null)
{
throw new InvalidOperationException(
RelationalStrings.DbFunctionInvalidReturnEntityType(
dbFunction.ModelName, dbFunction.ReturnType.ShortDisplayName(), elementType.ShortDisplayName()));
}
if ((entityType.BaseType != null || entityType.GetDerivedTypes().Any())
&& entityType.FindDiscriminatorProperty() == null)
{
throw new InvalidOperationException(
RelationalStrings.TableValuedFunctionNonTph(dbFunction.ModelName, entityType.DisplayName()));
}
}
foreach (var parameter in dbFunction.Parameters)
{
if (parameter.TypeMapping == null)
{
throw new InvalidOperationException(
RelationalStrings.DbFunctionInvalidParameterType(
parameter.Name,
dbFunction.ModelName,
parameter.ClrType.ShortDisplayName()));
}
}
}
///
/// Validates the function mapping for an entity type.
///
/// The entity type to validate.
/// The logger to use.
protected virtual void ValidateDbFunctionMapping(
IEntityType entityType,
IDiagnosticsLogger logger)
{
var mappedFunctionName = entityType.GetFunctionName();
if (mappedFunctionName == null)
{
return;
}
var mappedFunction = entityType.Model.FindDbFunction(mappedFunctionName);
if (mappedFunction == null)
{
throw new InvalidOperationException(
RelationalStrings.MappedFunctionNotFound(entityType.DisplayName(), mappedFunctionName));
}
if (entityType.BaseType != null)
{
throw new InvalidOperationException(
RelationalStrings.InvalidMappedFunctionDerivedType(
entityType.DisplayName(), mappedFunctionName, entityType.BaseType.DisplayName()));
}
if (mappedFunction.IsScalar
|| mappedFunction.ReturnType.GetGenericArguments()[0] != entityType.ClrType)
{
throw new InvalidOperationException(
RelationalStrings.InvalidMappedFunctionUnmatchedReturn(
entityType.DisplayName(),
mappedFunctionName,
mappedFunction.ReturnType.ShortDisplayName(),
entityType.ClrType.ShortDisplayName()));
}
if (mappedFunction.Parameters.Count > 0)
{
var parameters = "{"
+ string.Join(
", ",
mappedFunction.Parameters.Select(p => "'" + p.Name + "'"))
+ "}";
throw new InvalidOperationException(
RelationalStrings.InvalidMappedFunctionWithParameters(
entityType.DisplayName(), mappedFunctionName, parameters));
}
}
///
/// Validates the stored procedures for an entity type.
///
/// The entity type to validate.
/// The logger to use.
protected virtual void ValidateStoredProcedures(
IEntityType entityType,
IDiagnosticsLogger logger)
{
var mappingStrategy = entityType.GetMappingStrategy() ?? RelationalAnnotationNames.TphMappingStrategy;
var sprocCount = 0;
var deleteStoredProcedure = entityType.GetDeleteStoredProcedure();
if (deleteStoredProcedure != null)
{
ValidateStoredProcedureName(StoreObjectType.DeleteStoredProcedure, entityType);
ValidateSproc(deleteStoredProcedure, mappingStrategy, logger);
sprocCount++;
}
var insertStoredProcedure = entityType.GetInsertStoredProcedure();
if (insertStoredProcedure != null)
{
ValidateStoredProcedureName(StoreObjectType.InsertStoredProcedure, entityType);
ValidateSproc(insertStoredProcedure, mappingStrategy, logger);
sprocCount++;
}
var updateStoredProcedure = entityType.GetUpdateStoredProcedure();
if (updateStoredProcedure != null)
{
ValidateStoredProcedureName(StoreObjectType.UpdateStoredProcedure, entityType);
ValidateSproc(updateStoredProcedure, mappingStrategy, logger);
sprocCount++;
}
if (sprocCount > 0
// TODO: Support this with #28703
//&& sprocCount < 3
&& entityType.GetTableName() == null)
{
throw new InvalidOperationException(RelationalStrings.StoredProcedureUnmapped(entityType.DisplayName()));
}
static void ValidateStoredProcedureName(
StoreObjectType storedProcedureType,
IEntityType entityType)
{
var sprocId = StoreObjectIdentifier.Create(entityType, storedProcedureType);
if (sprocId == null)
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureNoName(
entityType.DisplayName(), storedProcedureType));
}
}
}
///
/// Validates a single stored procedure and all entity types mapped to it.
///
/// The entity types mapped to the stored procedure.
/// The stored procedure identifier.
/// The logger to use.
protected virtual void ValidateStoredProcedure(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier storedProcedure,
IDiagnosticsLogger logger)
=> ValidateStoredProcedureCompatibility(mappedTypes, storedProcedure, logger);
///
/// Validates that a stored procedure is not shared across unrelated entity types.
///
/// The entity types mapped to the stored procedure.
/// The stored procedure identifier.
/// The logger to use.
protected virtual void ValidateStoredProcedureCompatibility(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier storedProcedure,
IDiagnosticsLogger logger)
{
foreach (var mappedType in mappedTypes)
{
if (mappedTypes[0].GetRootType() != mappedType.GetRootType())
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureTableSharing(
mappedTypes[0].DisplayName(),
mappedType.DisplayName(),
storedProcedure.DisplayName()));
}
}
}
private static void ValidateSproc(
IStoredProcedure sproc,
string mappingStrategy,
IDiagnosticsLogger logger)
{
var entityType = sproc.EntityType;
var storeObjectIdentifier = sproc.GetStoreIdentifier();
var primaryKey = entityType.FindPrimaryKey();
if (primaryKey == null)
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureKeyless(
entityType.DisplayName(), storeObjectIdentifier.DisplayName()));
}
var properties = entityType.GetDeclaredProperties().ToDictionary(p => p.Name);
if (mappingStrategy == RelationalAnnotationNames.TphMappingStrategy)
{
if (entityType.BaseType != null)
{
return;
}
foreach (var property in entityType.GetDerivedProperties())
{
properties.Add(property.Name, property);
}
}
else if (mappingStrategy == RelationalAnnotationNames.TpcMappingStrategy)
{
if (entityType.BaseType != null)
{
foreach (var property in entityType.BaseType.GetProperties())
{
properties.Add(property.Name, property);
}
}
}
else if (mappingStrategy == RelationalAnnotationNames.TptMappingStrategy)
{
var baseType = entityType.BaseType;
if (baseType != null)
{
foreach (var property in primaryKey.Properties)
{
properties.Add(property.Name, property);
}
while (baseType != null && baseType.IsAbstract())
{
if (StoredProcedure.FindDeclaredStoredProcedure(baseType, storeObjectIdentifier.StoreObjectType) != null)
{
break;
}
foreach (var property in baseType.GetDeclaredProperties())
{
if (property.IsPrimaryKey())
{
continue;
}
properties.Add(property.Name, property);
}
baseType = baseType.BaseType;
}
}
}
var storeGeneratedProperties = storeObjectIdentifier.StoreObjectType switch
{
StoreObjectType.InsertStoredProcedure
=> properties.Where(p => p.Value.ValueGenerated.HasFlag(ValueGenerated.OnAdd)).ToDictionary(),
StoreObjectType.UpdateStoredProcedure
=> properties.Where(p => p.Value.ValueGenerated.HasFlag(ValueGenerated.OnUpdate)).ToDictionary(),
_ => []
};
if (mappingStrategy == RelationalAnnotationNames.TptMappingStrategy
&& storeObjectIdentifier.StoreObjectType == StoreObjectType.InsertStoredProcedure
&& entityType.BaseType?.GetInsertStoredProcedure() != null)
{
foreach (var property in primaryKey.Properties)
{
storeGeneratedProperties.Remove(property.Name);
}
}
var resultColumnNames = new HashSet();
foreach (var resultColumn in sproc.ResultColumns)
{
IProperty? property = null!;
if (resultColumn.PropertyName != null
&& !properties.TryGetValue(resultColumn.PropertyName, out property))
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureResultColumnNotFound(
resultColumn.PropertyName, entityType.DisplayName(), storeObjectIdentifier.DisplayName()));
}
if (!resultColumnNames.Add(resultColumn.Name))
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureDuplicateResultColumnName(
resultColumn.Name, storeObjectIdentifier.DisplayName()));
}
if (resultColumn.PropertyName == null)
{
continue;
}
switch (storeObjectIdentifier.StoreObjectType)
{
case StoreObjectType.InsertStoredProcedure:
case StoreObjectType.UpdateStoredProcedure:
if (!storeGeneratedProperties.ContainsKey(property.Name))
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureResultColumnNotGenerated(
entityType.DisplayName(), resultColumn.PropertyName, storeObjectIdentifier.DisplayName()));
}
break;
case StoreObjectType.DeleteStoredProcedure:
throw new InvalidOperationException(
RelationalStrings.StoredProcedureResultColumnDelete(
entityType.DisplayName(), resultColumn.PropertyName, storeObjectIdentifier.DisplayName()));
default:
Check.DebugFail("Unexpected stored procedure type: " + storeObjectIdentifier.StoreObjectType);
break;
}
}
var originalValueProperties = new Dictionary(properties);
var parameterNames = new HashSet();
foreach (var parameter in sproc.Parameters)
{
IProperty? property = null;
if (parameter.PropertyName != null)
{
if (parameter.ForOriginalValue == true)
{
if (!originalValueProperties.TryGetAndRemove(parameter.PropertyName, out property))
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureParameterNotFound(
parameter.PropertyName, entityType.DisplayName(), storeObjectIdentifier.DisplayName()));
}
if (storeObjectIdentifier.StoreObjectType == StoreObjectType.InsertStoredProcedure)
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureOriginalValueParameterOnInsert(
parameter.Name, storeObjectIdentifier.DisplayName()));
}
}
else
{
if (!properties.TryGetAndRemove(parameter.PropertyName, out property))
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureParameterNotFound(
parameter.PropertyName, entityType.DisplayName(), storeObjectIdentifier.DisplayName()));
}
if (storeObjectIdentifier.StoreObjectType == StoreObjectType.DeleteStoredProcedure)
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureCurrentValueParameterOnDelete(
parameter.Name, storeObjectIdentifier.DisplayName()));
}
if (parameter.Direction.HasFlag(ParameterDirection.Input))
{
switch (storeObjectIdentifier.StoreObjectType)
{
case StoreObjectType.InsertStoredProcedure:
if (property.GetBeforeSaveBehavior() != PropertySaveBehavior.Save)
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureInputParameterForInsertNonSaveProperty(
parameter.Name,
storeObjectIdentifier.DisplayName(),
parameter.PropertyName,
entityType.DisplayName(),
property.GetBeforeSaveBehavior()));
}
break;
case StoreObjectType.UpdateStoredProcedure:
if (property.GetAfterSaveBehavior() != PropertySaveBehavior.Save)
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureInputParameterForUpdateNonSaveProperty(
parameter.Name,
storeObjectIdentifier.DisplayName(),
parameter.PropertyName,
entityType.DisplayName(),
property.GetAfterSaveBehavior()));
}
break;
case StoreObjectType.DeleteStoredProcedure:
break;
default:
Check.DebugFail("Unexpected stored procedure type: " + storeObjectIdentifier.StoreObjectType);
break;
}
}
}
}
if (!parameterNames.Add(parameter.Name))
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureDuplicateParameterName(
parameter.Name, storeObjectIdentifier.DisplayName()));
}
if (parameter.PropertyName == null)
{
continue;
}
switch (storeObjectIdentifier.StoreObjectType)
{
case StoreObjectType.InsertStoredProcedure:
case StoreObjectType.UpdateStoredProcedure:
if (parameter.Direction != ParameterDirection.Input
&& !storeGeneratedProperties.Remove(property!.Name))
{
if (sproc.Parameters.Any(p => p.PropertyName == property.Name
&& p.ForOriginalValue != parameter.ForOriginalValue
&& p.Direction != ParameterDirection.Input))
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureOutputParameterConflict(
entityType.DisplayName(), parameter.PropertyName, storeObjectIdentifier.DisplayName()));
}
throw new InvalidOperationException(
RelationalStrings.StoredProcedureOutputParameterNotGenerated(
entityType.DisplayName(), parameter.PropertyName, storeObjectIdentifier.DisplayName()));
}
break;
case StoreObjectType.DeleteStoredProcedure:
if (!property!.IsPrimaryKey()
&& !property.IsConcurrencyToken)
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureDeleteNonKeyProperty(
entityType.DisplayName(), parameter.PropertyName, storeObjectIdentifier.DisplayName()));
}
break;
default:
Check.DebugFail("Unexpected stored procedure type: " + storeObjectIdentifier.StoreObjectType);
break;
}
}
foreach (var resultColumn in sproc.ResultColumns)
{
if (resultColumn.PropertyName == null)
{
continue;
}
properties.Remove(resultColumn.PropertyName);
if (!storeGeneratedProperties.Remove(resultColumn.PropertyName))
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureResultColumnParameterConflict(
entityType.DisplayName(), resultColumn.PropertyName, storeObjectIdentifier.DisplayName()));
}
}
if (storeGeneratedProperties.Count > 0)
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureGeneratedPropertiesNotMapped(
entityType.DisplayName(),
storeObjectIdentifier.DisplayName(),
storeGeneratedProperties.Values.Format()));
}
if (properties.Count > 0)
{
foreach (var property in properties.Values.ToList())
{
switch (storeObjectIdentifier.StoreObjectType)
{
case StoreObjectType.InsertStoredProcedure:
if ((property.ValueGenerated & ValueGenerated.OnAdd) == 0
&& property.GetBeforeSaveBehavior() != PropertySaveBehavior.Save)
{
properties.Remove(property.Name);
}
break;
case StoreObjectType.DeleteStoredProcedure:
if (!property.IsPrimaryKey()
&& !property.IsConcurrencyToken)
{
properties.Remove(property.Name);
}
break;
case StoreObjectType.UpdateStoredProcedure:
if (!property.IsPrimaryKey()
&& !property.IsConcurrencyToken
&& (property.ValueGenerated & ValueGenerated.OnUpdate) == 0
&& property.GetAfterSaveBehavior() != PropertySaveBehavior.Save)
{
properties.Remove(property.Name);
}
break;
}
}
foreach (var property in properties.Keys.ToList())
{
if (!originalValueProperties.ContainsKey(property))
{
properties.Remove(property);
}
}
if (properties.Count > 0)
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedurePropertiesNotMapped(
entityType.DisplayName(),
storeObjectIdentifier.DisplayName(),
properties.Values.Format()));
}
}
if (sproc.IsRowsAffectedReturned
|| sproc.FindRowsAffectedParameter() != null
|| sproc.FindRowsAffectedResultColumn() != null)
{
if (storeObjectIdentifier.StoreObjectType == StoreObjectType.InsertStoredProcedure)
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureRowsAffectedForInsert(
storeObjectIdentifier.DisplayName()));
}
if (originalValueProperties.Values.FirstOrDefault(p => p.IsConcurrencyToken) is { } missedConcurrencyToken)
{
logger.StoredProcedureConcurrencyTokenNotMapped(entityType, missedConcurrencyToken, storeObjectIdentifier.DisplayName());
}
if (sproc.ResultColumns.Any(c => c != sproc.FindRowsAffectedResultColumn()))
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureRowsAffectedWithResultColumns(
entityType.DisplayName(),
storeObjectIdentifier.DisplayName()));
}
}
}
///
/// Validates a property with defaults.
///
/// The property to validate.
/// The logger to use.
protected virtual void ValidateBoolWithDefaults(
IProperty property,
IDiagnosticsLogger logger)
{
if (!property.ClrType.IsNullableType()
&& (property.ClrType.IsEnum || property.ClrType == typeof(bool))
&& property.ValueGenerated != ValueGenerated.Never
&& property.FieldInfo?.FieldType.IsNullableType() != true
&& !((IConventionProperty)property).GetSentinelConfigurationSource().HasValue
&& StoreObjectIdentifier.Create(property.DeclaringType, StoreObjectType.Table) is { } table
&& (IsNotNullAndNotDefault(property.GetDefaultValue(table))
|| property.GetDefaultValueSql(table) != null))
{
logger.BoolWithDefaultWarning(property);
}
bool IsNotNullAndNotDefault(object? value)
=> value != null
#pragma warning disable EF1001 // Internal EF Core API usage.
&& !property.ClrType.IsDefaultValue(value);
#pragma warning restore EF1001 // Internal EF Core API usage.
}
///
/// Validates default values on a key.
///
/// The key to validate.
/// The logger to use.
protected virtual void ValidateDefaultValuesOnKey(
IKey key,
IDiagnosticsLogger logger)
{
IProperty? propertyWithDefault = null;
foreach (var property in key.Properties)
{
var defaultValue = (IConventionAnnotation?)property.FindAnnotation(RelationalAnnotationNames.DefaultValue);
if (!property.IsForeignKey()
&& defaultValue?.Value != null
&& defaultValue.GetConfigurationSource().Overrides(ConfigurationSource.DataAnnotation))
{
propertyWithDefault ??= property;
}
else
{
propertyWithDefault = null;
break;
}
}
if (propertyWithDefault != null)
{
logger.ModelValidationKeyDefaultValueWarning(propertyWithDefault);
}
}
///
/// Validates that a key doesn't have mutable properties.
///
/// The key to validate.
/// The logger to use.
protected override void ValidateMutableKey(
IKey key,
IDiagnosticsLogger logger)
{
var mutableProperty = key.Properties.FirstOrDefault(p => p.ValueGenerated.HasFlag(ValueGenerated.OnUpdate));
if (mutableProperty != null
&& !mutableProperty.IsOrdinalKeyProperty())
{
throw new InvalidOperationException(CoreStrings.MutableKeyProperty(mutableProperty.Name));
}
}
///
/// Validates a single table and all entity types mapped to it.
///
/// The entity types mapped to the table.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateTable(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
{
var nonJsonMappedTypes = mappedTypes.Where(e => !e.IsMappedToJson()).ToList();
if (nonJsonMappedTypes.Count > 0)
{
ValidateSharedTableCompatibility(nonJsonMappedTypes, table, logger);
ValidateSharedColumnsCompatibility(nonJsonMappedTypes, table, logger);
ValidateSharedKeysCompatibility(nonJsonMappedTypes, table, logger);
ValidateSharedForeignKeysCompatibility(nonJsonMappedTypes, table, logger);
ValidateSharedIndexesCompatibility(nonJsonMappedTypes, table, logger);
ValidateSharedCheckConstraintCompatibility(nonJsonMappedTypes, table, logger);
ValidateSharedTriggerCompatibility(nonJsonMappedTypes, table, logger);
ValidateOptionalDependents(nonJsonMappedTypes, table, logger);
}
ValidateJsonColumns(mappedTypes, table, logger);
}
///
/// Validates the JSON-mapped owned entity types and complex properties in the given table, including that they aren't
/// mapped to the same JSON column, except for complex properties on types that can't share a row.
///
/// The entity types mapped to the table.
/// The identifier of the table.
/// The logger to use.
protected virtual void ValidateJsonColumns(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
{
var jsonColumns = new Dictionary>();
var complexProperties = new HashSet();
var hasJsonEntityTypes = false;
foreach (var entityType in mappedTypes)
{
if (entityType.IsMappedToJson())
{
hasJsonEntityTypes = true;
ValidateJsonOwnedEntityType(entityType, table, logger);
if (!entityType.FindOwnership()!.PrincipalEntityType.IsMappedToJson())
{
Validate(entityType, entityType.GetContainerColumnName()!, jsonColumns, table);
}
continue;
}
// Inherited complex properties are reached through each type in the table, but are only mapped once
foreach (var complexProperty in entityType.GetComplexProperties())
{
if (complexProperties.Add(complexProperty))
{
ValidateComplexProperty(complexProperty, jsonColumns, table);
}
}
}
if (hasJsonEntityTypes)
{
var nonOwnedTypes = mappedTypes.Where(x => !x.IsOwned());
var nonOwnedTypesCount = nonOwnedTypes.Count();
if (nonOwnedTypesCount == 0)
{
var nonJsonType = mappedTypes.FirstOrDefault(x => !x.IsMappedToJson());
if (nonJsonType != null)
{
// must be an owned collection (mapped to a separate table) that owns a JSON type
// Issue #28441
throw new InvalidOperationException(
RelationalStrings.JsonEntityOwnedByNonJsonOwnedType(
nonJsonType.DisplayName(), table.DisplayName()));
}
}
var distinctRootTypes = nonOwnedTypes.Select(x => x.GetRootType()).Distinct().ToList();
if (distinctRootTypes.Count > 1)
{
// Issue #28442
throw new InvalidOperationException(
RelationalStrings.JsonEntityWithTableSplittingIsNotSupported);
}
ValidateJsonEntityRoot(table, distinctRootTypes[0]);
}
return;
static void ValidateComplexProperty(
IComplexProperty complexProperty,
Dictionary> jsonColumns,
in StoreObjectIdentifier table)
{
if (complexProperty.ComplexType.GetContainerColumnName() == null)
{
foreach (var nestedComplexProperty in complexProperty.ComplexType.GetComplexProperties())
{
ValidateComplexProperty(nestedComplexProperty, jsonColumns, table);
}
return;
}
// The JSON column of an inherited complex property can be in another table, e.g. with TPT
var columnName = complexProperty.ComplexType.GetContainerColumnName(table);
if (columnName != null)
{
Validate(complexProperty.ComplexType, columnName, jsonColumns, table);
}
}
static void Validate(
ITypeBase jsonType,
string columnName,
Dictionary> jsonColumns,
in StoreObjectIdentifier table)
{
if (!jsonColumns.TryGetValue(columnName, out var existingJsonTypes))
{
jsonColumns[columnName] = [jsonType];
return;
}
foreach (var existingJsonType in existingJsonTypes)
{
if (jsonType is not IComplexType complexType
|| existingJsonType is not IComplexType existingComplexType)
{
// Issue #28592
// TODO: handle JSON columns on views, issue #28584
throw new InvalidOperationException(
RelationalStrings.JsonEntityMultipleRootsMappedToTheSameJsonColumn(columnName, table.Name));
}
// Only types in different branches of the same hierarchy never share a row, so they can share the column.
// Unrelated types sharing the table, e.g. a principal and dependent, share a row. Dependents of sibling types don't,
// but querying a dependent doesn't filter by its principal's type, so it would read the other type's JSON.
var rootType = GetRootPrincipal(complexType.ContainingEntityType);
var existingRootType = GetRootPrincipal(existingComplexType.ContainingEntityType);
if (rootType.GetRootType() != existingRootType.GetRootType()
|| rootType.IsAssignableFrom(existingRootType)
|| existingRootType.IsAssignableFrom(rootType))
{
throw new InvalidOperationException(
RelationalStrings.ComplexPropertiesSharedJsonColumn(
$"{existingComplexType.ComplexProperty.DeclaringType.DisplayName()}.{existingComplexType.ComplexProperty.Name}",
$"{complexType.ComplexProperty.DeclaringType.DisplayName()}.{complexType.ComplexProperty.Name}",
columnName,
table.DisplayName()));
}
// Sibling types can't map a complex collection and a non-collection complex property to the same JSON column
if (complexType.ComplexProperty.IsCollection != existingComplexType.ComplexProperty.IsCollection)
{
var (complexCollection, complexProperty) = complexType.ComplexProperty.IsCollection
? (complexType.ComplexProperty, existingComplexType.ComplexProperty)
: (existingComplexType.ComplexProperty, complexType.ComplexProperty);
throw new InvalidOperationException(
RelationalStrings.ComplexCollectionSharedJsonColumn(
$"{complexCollection.DeclaringType.DisplayName()}.{complexCollection.Name}",
$"{complexProperty.DeclaringType.DisplayName()}.{complexProperty.Name}",
columnName,
table.DisplayName()));
}
}
existingJsonTypes.Add(jsonType);
}
static IEntityType GetRootPrincipal(IEntityType entityType)
{
while (entityType.FindOwnership() is { } ownership)
{
entityType = ownership.PrincipalEntityType;
}
return entityType;
}
}
///
/// Validates that optional dependents have an identifying non-nullable property.
///
/// The mapped entity types.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateOptionalDependents(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
{
if (mappedTypes.Count == 1)
{
return;
}
var tableIdentifier = table;
var principalEntityTypesMap = new Dictionary EntityTypes, bool Optional)>();
foreach (var entityType in mappedTypes)
{
if (entityType.BaseType != null
|| entityType.FindPrimaryKey() == null)
{
continue;
}
var (principalEntityTypes, optional) = GetPrincipalEntityTypes(entityType);
if (!optional)
{
continue;
}
var principalColumns = principalEntityTypes.SelectMany(e => e.GetProperties())
.Select(e => e.GetColumnName(tableIdentifier))
.Where(e => e != null)
.ToList();
var requiredNonSharedColumnFound = entityType.GetRequiredNonPkProperties().Any(p => p switch
{
IProperty property => property.GetColumnName(tableIdentifier),
IComplexProperty complexProperty => complexProperty.ComplexType.GetContainerColumnName(tableIdentifier),
_ => null
} is { } columnName
&& !principalColumns.Contains(columnName));
if (!requiredNonSharedColumnFound)
{
if (entityType.GetReferencingForeignKeys().Select(e => e.DeclaringEntityType).Any(t => mappedTypes.Contains(t)))
{
throw new InvalidOperationException(
RelationalStrings.OptionalDependentWithDependentWithoutIdentifyingProperty(entityType.DisplayName()));
}
logger.OptionalDependentWithoutIdentifyingPropertyWarning(entityType);
}
}
(List EntityTypes, bool Optional) GetPrincipalEntityTypes(IEntityType entityType)
{
if (!principalEntityTypesMap.TryGetValue(entityType, out var tuple))
{
var list = new List();
var optional = false;
foreach (var foreignKey in entityType.FindForeignKeys(entityType.FindPrimaryKey()!.Properties))
{
var principalEntityType = foreignKey.PrincipalEntityType;
if (foreignKey.PrincipalEntityType.IsAssignableFrom(foreignKey.DeclaringEntityType)
|| !mappedTypes.Contains(principalEntityType))
{
continue;
}
list.Add(principalEntityType);
var (entityTypes, _) = GetPrincipalEntityTypes(principalEntityType.GetRootType());
list.AddRange(entityTypes);
optional |= !foreignKey.IsRequiredDependent;
}
tuple = (list, optional);
principalEntityTypesMap.Add(entityType, tuple);
}
return tuple;
}
}
///
/// Validates the compatibility of entity types sharing a given table.
///
/// The mapped entity types.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateSharedTableCompatibility(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
{
if (mappedTypes.Count == 1)
{
return;
}
var unvalidatedTypes = new HashSet(mappedTypes);
IEntityType? root = null;
foreach (var mappedType in mappedTypes)
{
if (mappedType.BaseType != null && unvalidatedTypes.Contains(mappedType.BaseType))
{
continue;
}
var primaryKey = mappedType.FindPrimaryKey();
if (primaryKey != null
&& (mappedType.FindForeignKeys(primaryKey.Properties)
.FirstOrDefault(fk => fk.PrincipalKey.IsPrimaryKey()
&& !fk.PrincipalEntityType.IsAssignableFrom(fk.DeclaringEntityType)
&& unvalidatedTypes.Contains(fk.PrincipalEntityType)) is { } linkingFK))
{
if (mappedType.BaseType != null)
{
throw new InvalidOperationException(
RelationalStrings.IncompatibleTableDerivedRelationship(
table.DisplayName(),
mappedType.DisplayName(),
linkingFK.PrincipalEntityType.DisplayName()));
}
continue;
}
if (root != null)
{
throw new InvalidOperationException(
RelationalStrings.IncompatibleTableNoRelationship(
table.DisplayName(),
mappedType.DisplayName(),
root.DisplayName()));
}
root = mappedType;
}
Check.DebugAssert(root != null);
unvalidatedTypes.Remove(root);
var typesToValidate = new Queue();
typesToValidate.Enqueue(root);
while (typesToValidate.Count > 0)
{
var entityType = typesToValidate.Dequeue();
var key = entityType.FindPrimaryKey();
var comment = entityType.GetComment();
var isExcluded = entityType.IsTableExcludedFromMigrations(table);
var typesToValidateLeft = typesToValidate.Count;
var directlyConnectedTypes = unvalidatedTypes.Where(unvalidatedType =>
entityType.IsAssignableFrom(unvalidatedType)
|| IsIdentifyingPrincipal(unvalidatedType, entityType));
foreach (var nextEntityType in directlyConnectedTypes)
{
if (key != null)
{
var otherKey = nextEntityType.FindPrimaryKey()!;
if (key.GetName(table) != otherKey.GetName(table))
{
throw new InvalidOperationException(
RelationalStrings.IncompatibleTableKeyNameMismatch(
table.DisplayName(),
entityType.DisplayName(),
nextEntityType.DisplayName(),
key.GetName(table),
key.Properties.Format(),
otherKey.GetName(table),
otherKey.Properties.Format()));
}
}
var nextComment = nextEntityType.GetComment();
if (comment != null)
{
if (nextComment != null
&& !comment.Equals(nextComment, StringComparison.Ordinal))
{
throw new InvalidOperationException(
RelationalStrings.IncompatibleTableCommentMismatch(
table.DisplayName(),
entityType.DisplayName(),
nextEntityType.DisplayName(),
comment,
nextComment));
}
}
else
{
comment = nextComment;
}
if (isExcluded.Equals(!nextEntityType.IsTableExcludedFromMigrations(table)))
{
throw new InvalidOperationException(
RelationalStrings.IncompatibleTableExcludedMismatch(
table.DisplayName(),
entityType.DisplayName(),
nextEntityType.DisplayName()));
}
typesToValidate.Enqueue(nextEntityType);
}
foreach (var typeToValidate in typesToValidate.Skip(typesToValidateLeft))
{
unvalidatedTypes.Remove(typeToValidate);
}
}
if (unvalidatedTypes.Count == 0)
{
return;
}
foreach (var invalidEntityType in unvalidatedTypes)
{
Check.DebugAssert(root != null, "root is null");
throw new InvalidOperationException(
RelationalStrings.IncompatibleTableNoRelationship(
table.DisplayName(),
invalidEntityType.DisplayName(),
root.DisplayName()));
}
}
///
/// Validates a single view and all entity types mapped to it.
///
/// The entity types mapped to the view.
/// The view identifier.
/// The logger to use.
protected virtual void ValidateView(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier view,
IDiagnosticsLogger logger)
{
var nonJsonMappedTypes = mappedTypes.Where(e => !e.IsMappedToJson()).ToList();
if (nonJsonMappedTypes.Count > 0)
{
ValidateSharedViewCompatibility(nonJsonMappedTypes, view.Name, view.Schema, logger);
ValidateSharedColumnsCompatibility(nonJsonMappedTypes, view, logger);
}
if (mappedTypes.Count != nonJsonMappedTypes.Count)
{
ValidateJsonView(mappedTypes, view, logger);
}
}
///
/// Validates the compatibility of entity types sharing a given view.
///
/// The mapped entity types.
/// The view name.
/// The schema.
/// The logger to use.
protected virtual void ValidateSharedViewCompatibility(
IReadOnlyList mappedTypes,
string viewName,
string? schema,
IDiagnosticsLogger logger)
{
if (mappedTypes.Count == 1)
{
return;
}
var storeObject = StoreObjectIdentifier.View(viewName, schema);
var unvalidatedTypes = new HashSet(mappedTypes);
IEntityType? root = null;
foreach (var mappedType in mappedTypes)
{
if (mappedType.BaseType != null && unvalidatedTypes.Contains(mappedType.BaseType))
{
continue;
}
if (mappedType.FindPrimaryKey() != null
&& mappedType.FindForeignKeys(mappedType.FindPrimaryKey()!.Properties)
.Any(fk => fk.PrincipalKey.IsPrimaryKey()
&& unvalidatedTypes.Contains(fk.PrincipalEntityType)))
{
if (mappedType.BaseType != null)
{
var principalType = mappedType.FindForeignKeys(mappedType.FindPrimaryKey()!.Properties)
.First(fk => fk.PrincipalKey.IsPrimaryKey()
&& unvalidatedTypes.Contains(fk.PrincipalEntityType))
.PrincipalEntityType;
throw new InvalidOperationException(
RelationalStrings.IncompatibleViewDerivedRelationship(
storeObject.DisplayName(),
mappedType.DisplayName(),
principalType.DisplayName()));
}
continue;
}
if (root != null)
{
throw new InvalidOperationException(
RelationalStrings.IncompatibleViewNoRelationship(
storeObject.DisplayName(),
mappedType.DisplayName(),
root.DisplayName()));
}
root = mappedType;
}
Check.DebugAssert(root != null);
unvalidatedTypes.Remove(root);
var typesToValidate = new Queue();
typesToValidate.Enqueue(root);
while (typesToValidate.Count > 0)
{
var entityType = typesToValidate.Dequeue();
var typesToValidateLeft = typesToValidate.Count;
var directlyConnectedTypes = unvalidatedTypes.Where(unvalidatedType =>
entityType.IsAssignableFrom(unvalidatedType)
|| IsIdentifyingPrincipal(unvalidatedType, entityType));
foreach (var nextEntityType in directlyConnectedTypes)
{
typesToValidate.Enqueue(nextEntityType);
}
foreach (var typeToValidate in typesToValidate.Skip(typesToValidateLeft))
{
unvalidatedTypes.Remove(typeToValidate);
}
}
if (unvalidatedTypes.Count == 0)
{
return;
}
foreach (var invalidEntityType in unvalidatedTypes)
{
Check.DebugAssert(root != null, "root is null");
throw new InvalidOperationException(
RelationalStrings.IncompatibleViewNoRelationship(
viewName,
invalidEntityType.DisplayName(),
root.DisplayName()));
}
}
private static bool IsIdentifyingPrincipal(IEntityType dependentEntityType, IEntityType principalEntityType)
=> dependentEntityType.FindForeignKeys(dependentEntityType.FindPrimaryKey()!.Properties)
.Any(fk => fk.PrincipalKey.IsPrimaryKey()
&& fk.PrincipalEntityType == principalEntityType);
///
/// Validates the compatibility of properties sharing columns in a given table-like object.
///
/// The mapped entity types.
/// The identifier of the store object.
/// The logger to use.
protected virtual void ValidateSharedColumnsCompatibility(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier storeObject,
IDiagnosticsLogger logger)
{
var concurrencyColumns = TableSharingConcurrencyTokenConvention.GetConcurrencyTokensMap(storeObject, mappedTypes);
HashSet? missingConcurrencyTokens = null;
if (concurrencyColumns != null
&& storeObject.StoreObjectType == StoreObjectType.Table)
{
missingConcurrencyTokens = [];
}
var propertyMappings = new Dictionary();
foreach (var entityType in mappedTypes)
{
if (missingConcurrencyTokens != null)
{
missingConcurrencyTokens.Clear();
foreach (var (concurrencyColumn, concurrencyProperties) in concurrencyColumns!)
{
if (TableSharingConcurrencyTokenConvention.IsConcurrencyTokenMissing(concurrencyProperties, entityType, mappedTypes))
{
missingConcurrencyTokens.Add(concurrencyColumn);
}
}
}
ValidateCompatible(entityType, storeObject, propertyMappings, missingConcurrencyTokens, logger);
if (missingConcurrencyTokens != null)
{
foreach (var concurrencyColumn in missingConcurrencyTokens)
{
throw new InvalidOperationException(
RelationalStrings.MissingConcurrencyColumn(
entityType.DisplayName(), concurrencyColumn, storeObject.DisplayName()));
}
}
}
var columnOrders = new Dictionary>();
foreach (var property in propertyMappings.Values)
{
var columnOrder = property.GetColumnOrder(storeObject);
if (!columnOrder.HasValue)
{
continue;
}
var columns = columnOrders.GetOrAddNew(columnOrder.Value);
columns.Add(property.GetColumnName(storeObject)!);
}
if (columnOrders.Any(g => g.Value.Count > 1))
{
logger.DuplicateColumnOrders(
storeObject,
columnOrders.Where(g => g.Value.Count > 1).SelectMany(g => g.Value).ToList());
}
return;
void ValidateCompatible(
ITypeBase structuralType,
in StoreObjectIdentifier storeObject,
Dictionary propertyMappings,
HashSet? missingConcurrencyTokens,
IDiagnosticsLogger logger)
{
foreach (var property in structuralType.GetProperties())
{
var columnName = property.GetColumnName(storeObject);
if (columnName == null)
{
continue;
}
missingConcurrencyTokens?.Remove(columnName);
if (!propertyMappings.TryGetValue(columnName, out var duplicateProperty))
{
propertyMappings[columnName] = property;
continue;
}
if (property == duplicateProperty)
{
continue;
}
var declaringEntityType = property.DeclaringType.ContainingEntityType;
var duplicateDeclaringEntityType = duplicateProperty.DeclaringType.ContainingEntityType;
if (declaringEntityType.IsAssignableFrom(duplicateDeclaringEntityType)
|| duplicateDeclaringEntityType.IsAssignableFrom(declaringEntityType))
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameSameHierarchy(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName()));
}
this.ValidateCompatible(property, duplicateProperty, columnName, storeObject, logger);
}
foreach (var complexProperty in structuralType.GetComplexProperties())
{
ValidateCompatible(complexProperty.ComplexType, storeObject, propertyMappings, missingConcurrencyTokens, logger);
}
}
}
///
/// Validates the compatibility of two properties mapped to the same column.
///
/// A property.
/// Another property.
/// The column name.
/// The identifier of the store object.
/// The logger to use.
protected virtual void ValidateCompatible(
IProperty property,
IProperty duplicateProperty,
string columnName,
in StoreObjectIdentifier storeObject,
IDiagnosticsLogger logger)
{
// NB: Properties can have different nullability, the resulting column will be non-nullable if any of the properties is non-nullable
var currentMaxLength = property.GetMaxLength(storeObject);
var previousMaxLength = duplicateProperty.GetMaxLength(storeObject);
if (currentMaxLength != previousMaxLength)
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameMaxLengthMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName(),
previousMaxLength,
currentMaxLength));
}
if (property.IsUnicode(storeObject) != duplicateProperty.IsUnicode(storeObject))
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameUnicodenessMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName()));
}
if (property.IsFixedLength(storeObject) != duplicateProperty.IsFixedLength(storeObject))
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameFixedLengthMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName()));
}
var currentPrecision = property.GetPrecision(storeObject);
var previousPrecision = duplicateProperty.GetPrecision(storeObject);
if (currentPrecision != previousPrecision)
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNamePrecisionMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName(),
currentPrecision,
previousPrecision));
}
var currentScale = property.GetScale(storeObject);
var previousScale = duplicateProperty.GetScale(storeObject);
if (currentScale != previousScale)
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameScaleMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName(),
currentScale,
previousScale));
}
if (property.IsConcurrencyToken != duplicateProperty.IsConcurrencyToken)
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameConcurrencyTokenMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName()));
}
var currentTypeString = property.GetColumnType(storeObject);
var previousTypeString = duplicateProperty.GetColumnType(storeObject);
if (!string.Equals(currentTypeString, previousTypeString, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameDataTypeMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName(),
previousTypeString,
currentTypeString));
}
var typeMapping = property.GetRelationalTypeMapping();
var duplicateTypeMapping = duplicateProperty.GetRelationalTypeMapping();
var currentProviderType = typeMapping.Converter?.ProviderClrType.UnwrapNullableType()
?? typeMapping.ClrType;
var previousProviderType = duplicateTypeMapping.Converter?.ProviderClrType.UnwrapNullableType()
?? duplicateTypeMapping.ClrType;
if (currentProviderType != previousProviderType
&& (property.IsKey()
|| duplicateProperty.IsKey()
|| property.IsForeignKey()
|| duplicateProperty.IsForeignKey()
|| (property.IsIndex() && property.GetContainingIndexes().Any(i => i.IsUnique))
|| (duplicateProperty.IsIndex() && duplicateProperty.GetContainingIndexes().Any(i => i.IsUnique))))
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameProviderTypeMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName(),
previousProviderType.ShortDisplayName(),
currentProviderType.ShortDisplayName()));
}
var currentComputedColumnSql = property.GetComputedColumnSql(storeObject) ?? "";
var previousComputedColumnSql = duplicateProperty.GetComputedColumnSql(storeObject) ?? "";
if (!currentComputedColumnSql.Equals(previousComputedColumnSql, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameComputedSqlMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName(),
previousComputedColumnSql,
currentComputedColumnSql));
}
var currentStored = property.GetIsStored(storeObject);
var previousStored = duplicateProperty.GetIsStored(storeObject);
if (currentStored != previousStored)
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameIsStoredMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName(),
previousStored,
currentStored));
}
var hasDefaultValue = property.TryGetDefaultValue(storeObject, out var currentDefaultValue);
var duplicateHasDefaultValue = duplicateProperty.TryGetDefaultValue(storeObject, out var previousDefaultValue);
if ((hasDefaultValue
|| duplicateHasDefaultValue)
&& !Equals(currentDefaultValue, previousDefaultValue))
{
currentDefaultValue = GetDefaultColumnValue(property, storeObject);
previousDefaultValue = GetDefaultColumnValue(duplicateProperty, storeObject);
if (!Equals(currentDefaultValue, previousDefaultValue))
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameDefaultSqlMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName(),
previousDefaultValue ?? "NULL",
currentDefaultValue ?? "NULL"));
}
}
var currentDefaultValueSql = property.GetDefaultValueSql(storeObject) ?? "";
var previousDefaultValueSql = duplicateProperty.GetDefaultValueSql(storeObject) ?? "";
if (!currentDefaultValueSql.Equals(previousDefaultValueSql, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameDefaultSqlMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName(),
previousDefaultValueSql,
currentDefaultValueSql));
}
var currentComment = property.GetComment(storeObject) ?? "";
var previousComment = duplicateProperty.GetComment(storeObject) ?? "";
if (!currentComment.Equals(previousComment, StringComparison.Ordinal))
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameCommentMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName(),
previousComment,
currentComment));
}
var currentCollation = property.GetCollation(storeObject) ?? "";
var previousCollation = duplicateProperty.GetCollation(storeObject) ?? "";
if (!currentCollation.Equals(previousCollation, StringComparison.Ordinal))
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameCollationMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName(),
previousCollation,
currentCollation));
}
var currentColumnOrder = property.GetColumnOrder(storeObject);
var previousColumnOrder = duplicateProperty.GetColumnOrder(storeObject);
if (currentColumnOrder != previousColumnOrder)
{
throw new InvalidOperationException(
RelationalStrings.DuplicateColumnNameOrderMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName(),
previousColumnOrder,
currentColumnOrder));
}
}
///
/// Returns the object that is used as the default value for the column the property is mapped to.
///
/// The property to get the default value for.
/// The identifier of the store object.
/// The object that is used as the default value for the column the property is mapped to.
protected virtual object? GetDefaultColumnValue(
IProperty property,
in StoreObjectIdentifier storeObject)
{
var value = property.GetDefaultValue(storeObject);
var converter = property.FindRelationalTypeMapping(storeObject)?.Converter;
return converter != null
? converter.ConvertToProvider(value)
: value;
}
///
/// Validates the compatibility of foreign keys in a given shared table.
///
/// The mapped entity types.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateSharedForeignKeysCompatibility(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
{
if (table.StoreObjectType != StoreObjectType.Table)
{
return;
}
var foreignKeyMappings = new Dictionary();
foreach (var foreignKey in mappedTypes.SelectMany(et => et.GetDeclaredForeignKeys()))
{
var principalTable = foreignKey.PrincipalKey.IsPrimaryKey()
? StoreObjectIdentifier.Create(foreignKey.PrincipalEntityType, StoreObjectType.Table)
: StoreObjectIdentifier.Create(foreignKey.PrincipalKey.DeclaringEntityType, StoreObjectType.Table);
if (principalTable == null)
{
continue;
}
var foreignKeyName = foreignKey.GetConstraintName(table, principalTable.Value, logger);
if (foreignKeyName == null)
{
continue;
}
if (!foreignKeyMappings.TryGetValue(foreignKeyName, out var duplicateForeignKey))
{
foreignKeyMappings[foreignKeyName] = foreignKey;
continue;
}
ValidateCompatible(foreignKey, duplicateForeignKey, foreignKeyName, table, logger);
}
}
///
/// Validates the compatibility of two foreign keys mapped to the same foreign key constraint.
///
/// A foreign key.
/// Another foreign key.
/// The foreign key constraint name.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateCompatible(
IForeignKey foreignKey,
IForeignKey duplicateForeignKey,
string foreignKeyName,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
=> foreignKey.AreCompatible(duplicateForeignKey, table, shouldThrow: true);
///
/// Validates the compatibility of indexes in a given shared table.
///
/// The mapped entity types.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateSharedIndexesCompatibility(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
{
var indexMappings = new Dictionary();
foreach (var index in mappedTypes.SelectMany(et => et.GetDeclaredIndexes()))
{
var indexName = index.GetDatabaseName(table);
if (indexName == null)
{
continue;
}
if (!indexMappings.TryGetValue(indexName, out var duplicateIndex))
{
indexMappings[indexName] = index;
continue;
}
ValidateCompatible(index, duplicateIndex, indexName, table, logger);
}
}
///
/// Validates the compatibility of two indexes mapped to the same table index.
///
/// An index.
/// Another index.
/// The name of the index.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateCompatible(
IIndex index,
IIndex duplicateIndex,
string indexName,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
=> index.AreCompatible(duplicateIndex, table, shouldThrow: true);
///
/// Validates the compatibility of primary and alternate keys in a given shared table.
///
/// The mapped entity types.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateSharedKeysCompatibility(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
{
var keyMappings = new Dictionary();
foreach (var key in mappedTypes.SelectMany(et => et.GetDeclaredKeys()))
{
var keyName = key.GetName(table, logger);
if (keyName == null)
{
continue;
}
if (!keyMappings.TryGetValue(keyName, out var duplicateKey))
{
keyMappings[keyName] = key;
continue;
}
ValidateCompatible(key, duplicateKey, keyName, table, logger);
}
}
///
/// Validates the compatibility of two keys mapped to the same unique constraint.
///
/// A key.
/// Another key.
/// The name of the unique constraint.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateCompatible(
IKey key,
IKey duplicateKey,
string keyName,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
=> key.AreCompatible(duplicateKey, table, shouldThrow: true);
///
/// Validates the compatibility of check constraints in a given shared table.
///
/// The mapped entity types.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateSharedCheckConstraintCompatibility(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
{
var checkConstraintMappings = new Dictionary();
foreach (var checkConstraint in mappedTypes.SelectMany(et => et.GetDeclaredCheckConstraints()))
{
var checkConstraintName = checkConstraint.GetName(table);
if (checkConstraintName == null)
{
continue;
}
if (!checkConstraintMappings.TryGetValue(checkConstraintName, out var duplicateCheckConstraint))
{
checkConstraintMappings[checkConstraintName] = checkConstraint;
continue;
}
ValidateCompatible(checkConstraint, duplicateCheckConstraint, checkConstraintName, table, logger);
}
}
///
/// Validates the compatibility of two check constraints with the same name.
///
/// A check constraint.
/// Another check constraint.
/// The name of the check constraint.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateCompatible(
ICheckConstraint checkConstraint,
ICheckConstraint duplicateCheckConstraint,
string indexName,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
=> CheckConstraint.AreCompatible(checkConstraint, duplicateCheckConstraint, table, shouldThrow: true);
///
/// Validates the compatibility of triggers in a given shared table.
///
/// The mapped entity types.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateSharedTriggerCompatibility(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
{
var triggerMappings = new Dictionary();
foreach (var trigger in mappedTypes.SelectMany(et => et.GetDeclaredTriggers()))
{
var triggerName = trigger.GetDatabaseName(table);
if (triggerName == null)
{
continue;
}
if (!triggerMappings.TryGetValue(triggerName, out var duplicateTrigger))
{
triggerMappings[triggerName] = trigger;
continue;
}
ValidateCompatible(trigger, duplicateTrigger, triggerName, table, logger);
}
}
///
/// Validates the compatibility of two trigger with the same name.
///
/// A trigger.
/// Another trigger.
/// The name of the trigger.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateCompatible(
ITrigger trigger,
ITrigger duplicateTrigger,
string indexName,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
{
}
///
/// Validates inheritance mapping for an entity type.
///
/// The entity type to validate.
/// The logger to use.
protected override void ValidateInheritanceMapping(
IEntityType entityType,
IDiagnosticsLogger logger)
{
var mappingStrategy = (string?)entityType[RelationalAnnotationNames.MappingStrategy];
if (mappingStrategy != null)
{
ValidateMappingStrategy(entityType, mappingStrategy);
var storeObjectName = entityType.GetSchemaQualifiedTableName()
?? entityType.GetSchemaQualifiedViewName()
?? entityType.GetFunctionName()
?? entityType.GetSqlQuery()
?? entityType.GetInsertStoredProcedure()?.GetSchemaQualifiedName()
?? entityType.GetDeleteStoredProcedure()?.GetSchemaQualifiedName()
?? entityType.GetUpdateStoredProcedure()?.GetSchemaQualifiedName();
if (mappingStrategy == RelationalAnnotationNames.TpcMappingStrategy
&& !entityType.ClrType.IsInstantiable()
&& storeObjectName != null)
{
throw new InvalidOperationException(
RelationalStrings.AbstractTpc(entityType.DisplayName(), storeObjectName));
}
}
if (entityType.BaseType != null)
{
if (mappingStrategy != null
&& mappingStrategy != (string?)entityType.BaseType[RelationalAnnotationNames.MappingStrategy])
{
throw new InvalidOperationException(
RelationalStrings.DerivedStrategy(entityType.DisplayName(), mappingStrategy));
}
return;
}
// Hierarchy mapping strategy must be the same across all types of mappings (only for root types)
if (entityType.FindDiscriminatorProperty() != null)
{
if (mappingStrategy is not null
and not RelationalAnnotationNames.TphMappingStrategy)
{
throw new InvalidOperationException(
RelationalStrings.NonTphMappingStrategy(mappingStrategy, entityType.DisplayName()));
}
ValidateTphMapping(entityType, StoreObjectType.Table);
ValidateTphMapping(entityType, StoreObjectType.View);
ValidateTphMapping(entityType, StoreObjectType.Function);
ValidateTphMapping(entityType, StoreObjectType.InsertStoredProcedure);
ValidateTphMapping(entityType, StoreObjectType.DeleteStoredProcedure);
ValidateTphMapping(entityType, StoreObjectType.UpdateStoredProcedure);
ValidateDiscriminatorValues(entityType);
}
else
{
if (mappingStrategy != RelationalAnnotationNames.TpcMappingStrategy
&& entityType.FindPrimaryKey() == null
&& entityType.GetDirectlyDerivedTypes().Any())
{
throw new InvalidOperationException(
RelationalStrings.KeylessMappingStrategy(
mappingStrategy ?? RelationalAnnotationNames.TptMappingStrategy, entityType.DisplayName()));
}
ValidateNonTphMapping(entityType, StoreObjectType.Table);
ValidateNonTphMapping(entityType, StoreObjectType.View);
ValidateNonTphMapping(entityType, StoreObjectType.InsertStoredProcedure);
ValidateNonTphMapping(entityType, StoreObjectType.DeleteStoredProcedure);
ValidateNonTphMapping(entityType, StoreObjectType.UpdateStoredProcedure);
var derivedTypes = entityType.GetDerivedTypesInclusive().ToList();
var discriminatorValues = new Dictionary();
foreach (var derivedType in derivedTypes)
{
foreach (var complexProperty in derivedType.GetDeclaredComplexProperties())
{
ValidateDiscriminatorValues(complexProperty.ComplexType);
}
var discriminatorValue = derivedType.GetDiscriminatorValue();
if (!derivedType.ClrType.IsInstantiable()
|| discriminatorValue is null)
{
continue;
}
if (discriminatorValue is not string valueString)
{
throw new InvalidOperationException(
RelationalStrings.NonTphDiscriminatorValueNotString(discriminatorValue, derivedType.DisplayName()));
}
if (discriminatorValues.TryGetValue(valueString, out var duplicateEntityType))
{
throw new InvalidOperationException(
RelationalStrings.EntityShortNameNotUnique(
derivedType.Name, discriminatorValue, duplicateEntityType.Name));
}
discriminatorValues[valueString] = derivedType;
}
}
}
///
/// Validates the key value generation is valid.
///
/// The key.
/// The logger to use.
protected virtual void ValidateValueGeneration(
IKey key,
IDiagnosticsLogger logger)
{
var entityType = key.DeclaringEntityType;
if (entityType.GetMappingStrategy() == RelationalAnnotationNames.TpcMappingStrategy
&& entityType.BaseType == null)
{
foreach (var storeGeneratedProperty in key.Properties.Where(p => (p.ValueGenerated & ValueGenerated.OnAdd) != 0))
{
logger.TpcStoreGeneratedIdentityWarning(storeGeneratedProperty);
}
}
}
///
/// Validates that the given mapping strategy is supported
///
/// The entity type.
/// The mapping strategy.
protected virtual void ValidateMappingStrategy(IEntityType entityType, string? mappingStrategy)
{
switch (mappingStrategy)
{
case RelationalAnnotationNames.TphMappingStrategy:
case RelationalAnnotationNames.TpcMappingStrategy:
case RelationalAnnotationNames.TptMappingStrategy:
break;
default:
throw new InvalidOperationException(
RelationalStrings.InvalidMappingStrategy(
mappingStrategy, entityType.DisplayName()));
}
}
private static void ValidateNonTphMapping(IEntityType rootEntityType, StoreObjectType storeObjectType)
{
var isTpc = rootEntityType.GetMappingStrategy() == RelationalAnnotationNames.TpcMappingStrategy;
var derivedTypes = new Dictionary();
foreach (var entityType in rootEntityType.GetDerivedTypesInclusive())
{
var storeObject = StoreObjectIdentifier.Create(entityType, storeObjectType);
if (storeObject == null)
{
var unmappedOwnedType = entityType.GetReferencingForeignKeys()
.Where(fk => fk.IsOwnership)
.Select(fk => fk.DeclaringEntityType)
.FirstOrDefault(owned => StoreObjectIdentifier.Create(owned, storeObjectType) == null
&& ((IConventionEntityType)owned).GetStoreObjectConfigurationSource(storeObjectType) == null
&& !owned.IsMappedToJson());
if (unmappedOwnedType != null
&& entityType.GetDerivedTypes().Any(derived => StoreObjectIdentifier.Create(derived, storeObjectType) != null))
{
throw new InvalidOperationException(
RelationalStrings.UnmappedNonTPHOwner(
entityType.DisplayName(),
unmappedOwnedType.FindOwnership()!.PrincipalToDependent?.Name,
unmappedOwnedType.DisplayName(),
storeObjectType));
}
continue;
}
if (derivedTypes.TryGetValue(storeObject.Value, out var otherType))
{
switch (storeObjectType)
{
case StoreObjectType.Table:
throw new InvalidOperationException(
RelationalStrings.NonTphTableClash(
entityType.DisplayName(), otherType.DisplayName(), storeObject.Value.DisplayName()));
case StoreObjectType.View:
throw new InvalidOperationException(
RelationalStrings.NonTphViewClash(
entityType.DisplayName(), otherType.DisplayName(), storeObject.Value.DisplayName()));
case StoreObjectType.InsertStoredProcedure:
case StoreObjectType.DeleteStoredProcedure:
case StoreObjectType.UpdateStoredProcedure:
throw new InvalidOperationException(
RelationalStrings.NonTphStoredProcedureClash(
entityType.DisplayName(), otherType.DisplayName(), storeObject.Value.DisplayName()));
}
}
if (isTpc)
{
var rowInternalFk = entityType.FindDeclaredReferencingRowInternalForeignKeys(storeObject.Value)
.FirstOrDefault();
if (rowInternalFk != null
&& entityType.GetDirectlyDerivedTypes().Any())
{
throw new InvalidOperationException(
RelationalStrings.TpcTableSharing(
rowInternalFk.DeclaringEntityType.DisplayName(),
storeObject.Value.DisplayName(),
rowInternalFk.PrincipalEntityType.DisplayName()));
}
}
derivedTypes[storeObject.Value] = entityType;
}
var rootStoreObject = StoreObjectIdentifier.Create(rootEntityType, storeObjectType);
if (rootStoreObject == null)
{
return;
}
if (rootEntityType.FindRowInternalForeignKeys(rootStoreObject.Value).Any()
&& derivedTypes.Count > 1
&& rootEntityType.GetMappingStrategy() == RelationalAnnotationNames.TpcMappingStrategy)
{
var derivedTypePair = derivedTypes.First(kv => kv.Value != rootEntityType);
throw new InvalidOperationException(
RelationalStrings.TpcTableSharingDependent(
rootEntityType.DisplayName(),
rootStoreObject.Value.DisplayName(),
derivedTypePair.Value.DisplayName(),
derivedTypePair.Key.DisplayName()));
}
}
private static void ValidateTphMapping(IEntityType rootEntityType, StoreObjectType storeObjectType)
{
var isSproc = storeObjectType is StoreObjectType.DeleteStoredProcedure
or StoreObjectType.InsertStoredProcedure
or StoreObjectType.UpdateStoredProcedure;
var rootSproc = isSproc ? StoredProcedure.FindDeclaredStoredProcedure(rootEntityType, storeObjectType) : null;
var rootId = StoreObjectIdentifier.Create(rootEntityType, storeObjectType);
foreach (var entityType in rootEntityType.GetDerivedTypes())
{
var entityId = StoreObjectIdentifier.Create(entityType, storeObjectType);
if (entityId == null)
{
continue;
}
if (rootId == entityId)
{
if (rootSproc != null)
{
var sproc = StoredProcedure.FindDeclaredStoredProcedure(entityType, storeObjectType);
if (sproc != null
&& sproc != rootSproc)
{
throw new InvalidOperationException(
RelationalStrings.StoredProcedureTphDuplicate(
entityType.DisplayName(), rootEntityType.DisplayName(), rootId?.DisplayName()));
}
}
continue;
}
switch (storeObjectType)
{
case StoreObjectType.Table:
throw new InvalidOperationException(
RelationalStrings.TphTableMismatch(
entityType.DisplayName(), entityId.Value.DisplayName(),
rootEntityType.DisplayName(), rootId?.DisplayName()));
case StoreObjectType.View:
throw new InvalidOperationException(
RelationalStrings.TphViewMismatch(
entityType.DisplayName(), entityId.Value.DisplayName(),
rootEntityType.DisplayName(), rootId?.DisplayName()));
case StoreObjectType.Function:
throw new InvalidOperationException(
RelationalStrings.TphDbFunctionMismatch(
entityType.DisplayName(), entityId.Value.DisplayName(),
rootEntityType.DisplayName(), rootId?.DisplayName()));
case StoreObjectType.InsertStoredProcedure:
case StoreObjectType.DeleteStoredProcedure:
case StoreObjectType.UpdateStoredProcedure:
throw new InvalidOperationException(
RelationalStrings.TphStoredProcedureMismatch(
entityType.DisplayName(), entityId.Value.DisplayName(),
rootEntityType.DisplayName(), rootId?.DisplayName()));
}
}
}
///
protected override bool IsRedundant(IForeignKey foreignKey)
=> base.IsRedundant(foreignKey)
&& !foreignKey.DeclaringEntityType.GetMappingFragments().Any();
///
/// Validates the mapping fragments for an entity type.
///
/// The entity type to validate.
/// The logger to use.
protected virtual void ValidateMappingFragment(
IEntityType entityType,
IDiagnosticsLogger logger)
{
var fragments = EntityTypeMappingFragment.Get(entityType);
if (fragments == null)
{
return;
}
if (entityType.BaseType != null
|| entityType.GetDirectlyDerivedTypes().Any())
{
throw new InvalidOperationException(
RelationalStrings.EntitySplittingHierarchy(entityType.DisplayName(), fragments.First().StoreObject.DisplayName()));
}
var anyTableFragments = false;
var anyViewFragments = false;
foreach (var fragment in fragments)
{
var mainStoreObject = StoreObjectIdentifier.Create(entityType, fragment.StoreObject.StoreObjectType);
if (mainStoreObject == null)
{
throw new InvalidOperationException(
RelationalStrings.EntitySplittingUnmappedMainFragment(
entityType.DisplayName(), fragment.StoreObject.DisplayName(), fragment.StoreObject.StoreObjectType));
}
if (fragment.StoreObject == mainStoreObject)
{
throw new InvalidOperationException(
RelationalStrings.EntitySplittingConflictingMainFragment(
entityType.DisplayName(), fragment.StoreObject.DisplayName()));
}
var rowInternalForeignKeys = entityType.FindRowInternalForeignKeys(fragment.StoreObject).ToList();
foreach (var foreignKey in rowInternalForeignKeys)
{
var principalMainFragment = StoreObjectIdentifier.Create(
foreignKey.PrincipalEntityType, fragment.StoreObject.StoreObjectType)!.Value;
if (principalMainFragment != mainStoreObject)
{
throw new InvalidOperationException(
RelationalStrings.EntitySplittingUnmatchedMainTableSplitting(
entityType.DisplayName(),
fragment.StoreObject.DisplayName(),
foreignKey.PrincipalEntityType.DisplayName(),
principalMainFragment.DisplayName()));
}
}
if (fragment.IsOptional
&& rowInternalForeignKeys.Count > 0)
{
throw new InvalidOperationException(
RelationalStrings.EntitySplittingOptionalFragmentSharedTable(
entityType.DisplayName(),
fragment.StoreObject.DisplayName(),
rowInternalForeignKeys[0].PrincipalEntityType.DisplayName()));
}
var propertiesFound = false;
foreach (var property in entityType.GetProperties())
{
var columnName = property.GetColumnName(fragment.StoreObject);
if (columnName == null)
{
if (property.IsPrimaryKey())
{
throw new InvalidOperationException(
RelationalStrings.EntitySplittingMissingPrimaryKey(
entityType.DisplayName(), fragment.StoreObject.DisplayName()));
}
continue;
}
if (!property.IsPrimaryKey())
{
propertiesFound = true;
if (fragment.IsOptional
&& !property.IsColumnNullable(fragment.StoreObject))
{
throw new InvalidOperationException(
RelationalStrings.EntitySplittingNonNullablePropertyOnOptionalFragment(
entityType.DisplayName(), fragment.StoreObject.DisplayName(), property.Name));
}
}
}
if (!propertiesFound)
{
throw new InvalidOperationException(
RelationalStrings.EntitySplittingMissingProperties(
entityType.DisplayName(), fragment.StoreObject.DisplayName()));
}
switch (fragment.StoreObject.StoreObjectType)
{
case StoreObjectType.Table:
anyTableFragments = true;
break;
case StoreObjectType.View:
anyViewFragments = true;
break;
}
}
if (anyTableFragments)
{
ValidateMainMapping(entityType, StoreObjectIdentifier.Create(entityType, StoreObjectType.Table)!.Value);
}
if (anyViewFragments)
{
ValidateMainMapping(entityType, StoreObjectIdentifier.Create(entityType, StoreObjectType.View)!.Value);
}
static StoreObjectIdentifier? ValidateMainMapping(IEntityType entityType, StoreObjectIdentifier mainObject)
{
var nonSharedRequiredPropertyFound =
entityType.FindRowInternalForeignKeys(mainObject).All(fk => fk.IsRequiredDependent);
var propertyFound = false;
foreach (var property in entityType.GetProperties())
{
if (property.IsPrimaryKey())
{
continue;
}
var columnName = property.GetColumnName(mainObject);
if (columnName != null)
{
propertyFound = true;
if (!nonSharedRequiredPropertyFound
&& !property.IsNullable
&& property.FindSharedStoreObjectRootProperty(mainObject) == null)
{
nonSharedRequiredPropertyFound = true;
}
}
}
if (!propertyFound)
{
throw new InvalidOperationException(
RelationalStrings.EntitySplittingMissingPropertiesMainFragment(
entityType.DisplayName(), mainObject.DisplayName()));
}
if (!nonSharedRequiredPropertyFound)
{
var rowInternalFk = entityType.FindRowInternalForeignKeys(mainObject).First(fk => !fk.IsRequiredDependent);
throw new InvalidOperationException(
RelationalStrings.EntitySplittingMissingRequiredPropertiesOptionalDependent(
entityType.DisplayName(), mainObject.DisplayName(),
$".Navigation(p => p.{rowInternalFk.PrincipalToDependent!.Name}).IsRequired()"));
}
return mainObject;
}
}
///
/// Validates a table-specific property override for a property.
///
/// The property to validate.
/// The property override to validate.
/// The logger to use.
protected virtual void ValidatePropertyOverride(
IProperty property,
IReadOnlyRelationalPropertyOverrides propertyOverride,
IDiagnosticsLogger logger)
{
if (GetAllMappedStoreObjects(property, propertyOverride.StoreObject.StoreObjectType)
.Any(o => o == propertyOverride.StoreObject))
{
return;
}
var storeObject = propertyOverride.StoreObject;
throw storeObject.StoreObjectType switch
{
StoreObjectType.Table => new InvalidOperationException(
RelationalStrings.TableOverrideMismatch(
property.DeclaringType.DisplayName() + "." + property.Name,
propertyOverride.StoreObject.DisplayName())),
StoreObjectType.View => new InvalidOperationException(
RelationalStrings.ViewOverrideMismatch(
property.DeclaringType.DisplayName() + "." + property.Name,
propertyOverride.StoreObject.DisplayName())),
StoreObjectType.SqlQuery => new InvalidOperationException(
RelationalStrings.SqlQueryOverrideMismatch(
property.DeclaringType.DisplayName() + "." + property.Name,
propertyOverride.StoreObject.DisplayName())),
StoreObjectType.Function => new InvalidOperationException(
RelationalStrings.FunctionOverrideMismatch(
property.DeclaringType.DisplayName() + "." + property.Name,
propertyOverride.StoreObject.DisplayName())),
StoreObjectType.InsertStoredProcedure or StoreObjectType.DeleteStoredProcedure or StoreObjectType.UpdateStoredProcedure => new
InvalidOperationException(
RelationalStrings.StoredProcedureOverrideMismatch(
property.DeclaringType.DisplayName() + "." + property.Name,
propertyOverride.StoreObject.DisplayName())),
_ => new NotSupportedException(storeObject.StoreObjectType.ToString()),
};
}
private static IEnumerable GetAllMappedStoreObjects(
IReadOnlyProperty property,
StoreObjectType storeObjectType)
{
var declaringType = property.DeclaringType;
// Complex types inherit their table mapping from the containing entity type
if (declaringType is IReadOnlyComplexType)
{
declaringType = property.DeclaringType.ContainingEntityType;
}
var mappingStrategy = declaringType.GetMappingStrategy();
if (property.IsPrimaryKey())
{
var declaringStoreObject = StoreObjectIdentifier.Create(declaringType, storeObjectType);
if (declaringStoreObject != null)
{
yield return declaringStoreObject.Value;
}
if (storeObjectType is StoreObjectType.Function or StoreObjectType.SqlQuery)
{
yield break;
}
foreach (var fragment in declaringType.GetMappingFragments(storeObjectType))
{
yield return fragment.StoreObject;
}
if (declaringType is IReadOnlyEntityType entityType)
{
foreach (var containingType in entityType.GetDerivedTypes())
{
var storeObject = StoreObjectIdentifier.Create(containingType, storeObjectType);
if (storeObject != null)
{
yield return storeObject.Value;
if (mappingStrategy == RelationalAnnotationNames.TphMappingStrategy)
{
yield break;
}
}
}
}
}
else
{
var declaringStoreObject = StoreObjectIdentifier.Create(declaringType, storeObjectType);
if (storeObjectType is StoreObjectType.Function or StoreObjectType.SqlQuery)
{
if (declaringStoreObject != null)
{
yield return declaringStoreObject.Value;
}
yield break;
}
if (declaringStoreObject != null)
{
var fragments = declaringType.GetMappingFragments(storeObjectType).ToList();
if (fragments.Count > 0)
{
var overrides = RelationalPropertyOverrides.Find(property, declaringStoreObject.Value);
if (overrides != null)
{
yield return declaringStoreObject.Value;
}
foreach (var fragment in fragments)
{
overrides = RelationalPropertyOverrides.Find(property, fragment.StoreObject);
if (overrides != null)
{
yield return fragment.StoreObject;
}
}
yield break;
}
yield return declaringStoreObject.Value;
if (mappingStrategy != RelationalAnnotationNames.TpcMappingStrategy)
{
yield break;
}
}
if (declaringType is not IReadOnlyEntityType entityType)
{
yield break;
}
var tableFound = false;
var queue = new Queue();
queue.Enqueue(entityType);
while (queue.Count > 0
&& (!tableFound || mappingStrategy == RelationalAnnotationNames.TpcMappingStrategy))
{
foreach (var containingType in queue.Dequeue().GetDirectlyDerivedTypes())
{
var storeObject = StoreObjectIdentifier.Create(containingType, storeObjectType);
if (storeObject != null)
{
yield return storeObject.Value;
tableFound = true;
if (mappingStrategy == RelationalAnnotationNames.TphMappingStrategy)
{
yield break;
}
}
if (!tableFound
|| mappingStrategy == RelationalAnnotationNames.TpcMappingStrategy)
{
queue.Enqueue(containingType);
}
}
}
}
}
///
/// Validates a single index.
///
/// The index to validate.
/// The logger to use.
protected override void ValidateIndex(
IIndex index,
IDiagnosticsLogger logger)
{
base.ValidateIndex(index, logger);
ValidateIndexPropertyMapping(index, logger);
ValidateJsonPathIndexSingleContainer(index);
}
private static void ValidateJsonPathIndexSingleContainer(IIndex index)
{
var table = StoreObjectIdentifier.Create(index.DeclaringEntityType, StoreObjectType.Table);
string? firstContainer = null;
for (var i = 0; i < index.Properties.Count; i++)
{
var property = index.Properties[i];
// Only properties mapped inside a JSON container matter here. Mixed JSON / non-JSON indexes
// are rejected earlier by ValidateIndexPropertyMapping.
var jsonComplexType = property.DeclaringType is IReadOnlyComplexType complexType && complexType.IsMappedToJson()
? complexType
: property is IReadOnlyComplexProperty complexProperty && complexProperty.ComplexType.IsMappedToJson()
? complexProperty.ComplexType
: null;
var container = (table is { } tableIdentifier ? jsonComplexType?.GetContainerColumnName(tableIdentifier) : null)
?? jsonComplexType?.GetContainerColumnName();
if (container is null)
{
// Not a JSON-contained property. If this position carries a non-null collection-indices
// entry (i.e., the path traverses a complex collection but doesn't end in JSON), the
// index identity points at a JSON path that has no JSON container — that's invalid.
if (index.CollectionIndices?[i] is not null)
{
throw new InvalidOperationException(
RelationalStrings.JsonPathIndexPropertyMissingJsonColumn(
index.Properties.Format(),
index.DeclaringEntityType.DisplayName(),
property.Name));
}
continue;
}
if (firstContainer is null)
{
firstContainer = container;
}
else if (!string.Equals(firstContainer, container, StringComparison.Ordinal))
{
throw new InvalidOperationException(
RelationalStrings.JsonPathIndexPropertiesInDifferentJsonColumns(
index.Properties.Format(),
index.DeclaringEntityType.DisplayName(),
firstContainer,
container));
}
}
}
///
protected override void ValidateIndexProperty(
IIndex index,
IPropertyBase property,
IDiagnosticsLogger logger)
{
// A property declared inside a JSON-mapped complex type is a valid index target: when the
// path traverses a collection the index is a JSON-path index (CollectionIndices is non-null,
// already enforced by Index construction); otherwise it's a scalar inside a JSON document.
// Either way, the base validator's complex-collection rejection does not apply.
var inJsonComplex = (property is IReadOnlyComplexProperty complexProperty
&& complexProperty.ComplexType.IsMappedToJson())
|| (property.DeclaringType is IReadOnlyComplexType complexType
&& complexType.IsMappedToJson());
if (inJsonComplex)
{
return;
}
base.ValidateIndexProperty(index, property, logger);
}
///
protected override void ValidateIndexOnComplexProperty(
IIndex index,
IReadOnlyList complexProperties,
IDiagnosticsLogger logger)
{
var nonJsonComplexProperty = complexProperties.FirstOrDefault(cp => !cp.ComplexType.IsMappedToJson());
if (nonJsonComplexProperty != null)
{
throw new InvalidOperationException(
RelationalStrings.IndexOnNonJsonComplexProperty(
index.Properties.Format(),
index.DeclaringEntityType.DisplayName(),
nonJsonComplexProperty.Name));
}
if (index.IsUnique)
{
// Currently not supported. We have special logic for unique indexes in the update pipeline
// and query that would need to be updated to support this.
throw new InvalidOperationException(
RelationalStrings.UniqueIndexOnComplexProperty(
index.Properties.Format(),
index.DeclaringEntityType.DisplayName(),
complexProperties[0].Name));
}
}
///
/// Validates that the properties of the index are all mapped to columns on a given table.
///
/// The index to validate.
/// The logger to use.
protected virtual void ValidateIndexPropertyMapping(
IIndex index,
IDiagnosticsLogger logger)
{
if (((IConventionIndex)index).GetConfigurationSource() == ConfigurationSource.Convention)
{
return;
}
var entityType = index.DeclaringEntityType;
IReadOnlyPropertyBase? propertyNotMappedToAnyTable = null;
(string, List)? firstPropertyTables = null;
(string, List)? lastPropertyTables = null;
HashSet? overlappingTables = null;
bool? anyJsonContained = null;
var allJsonContained = true;
foreach (var propertyBase in index.Properties)
{
var isJsonContained = false;
string propertyName = null!;
List tablesMappedToProperty = null!;
switch (propertyBase)
{
case IReadOnlyProperty { DeclaringType: IReadOnlyComplexType complexType } when complexType.IsMappedToJson():
{
isJsonContained = true;
break;
}
case IReadOnlyProperty property:
{
propertyName = property.Name;
tablesMappedToProperty = property.GetMappedStoreObjects(StoreObjectType.Table).ToList();
break;
}
case IReadOnlyComplexProperty complexProperty:
{
Check.DebugAssert(
complexProperty.ComplexType.IsMappedToJson(),
"Complex properties in indexes must be mapped to JSON at this point.");
if (complexProperty.DeclaringType is IReadOnlyComplexType declaringComplexType
&& declaringComplexType.IsMappedToJson())
{
isJsonContained = true;
}
else
{
propertyName = complexProperty.Name;
tablesMappedToProperty = complexProperty.GetMappedStoreObjects(StoreObjectType.Table).ToList();
}
break;
}
default:
throw new UnreachableException($"Properties of type {propertyBase.GetType().Name} are not supported in indexes.");
}
if (anyJsonContained != null && anyJsonContained != isJsonContained)
{
throw new InvalidOperationException(
RelationalStrings.IndexPropertiesMixedJsonAndNonJsonMapping(
index.Properties.Format(),
entityType.DisplayName()));
}
anyJsonContained = isJsonContained;
if (anyJsonContained == true)
{
continue;
}
allJsonContained = false;
if (tablesMappedToProperty.Count == 0)
{
propertyNotMappedToAnyTable = propertyBase;
overlappingTables = null;
if (firstPropertyTables != null)
{
// Property is not mapped but we already found a property that is mapped.
break;
}
continue;
}
if (firstPropertyTables == null)
{
firstPropertyTables = (propertyName, tablesMappedToProperty);
}
else
{
lastPropertyTables = (propertyName, tablesMappedToProperty);
}
if (propertyNotMappedToAnyTable != null)
{
// Property is mapped but we already found a property that is not mapped.
overlappingTables = null;
break;
}
if (overlappingTables == null)
{
overlappingTables = [.. tablesMappedToProperty];
}
else
{
overlappingTables.IntersectWith(tablesMappedToProperty);
if (overlappingTables.Count == 0)
{
break;
}
}
}
if (overlappingTables == null)
{
if (firstPropertyTables == null)
{
if (!allJsonContained)
{
logger.AllIndexPropertiesNotMappedToAnyTable(
entityType, index);
}
}
else
{
logger.IndexPropertiesBothMappedAndNotMappedToTable(
entityType, index, propertyNotMappedToAnyTable!.Name);
}
}
else if (overlappingTables.Count == 0)
{
Check.DebugAssert(firstPropertyTables != null);
Check.DebugAssert(lastPropertyTables != null);
logger.IndexPropertiesMappedToNonOverlappingTables(
entityType,
index,
firstPropertyTables.Value.Item1,
firstPropertyTables.Value.Item2.Select(t => (t.Name, t.Schema)).ToList(),
lastPropertyTables.Value.Item1,
lastPropertyTables.Value.Item2.Select(t => (t.Name, t.Schema)).ToList());
}
}
///
protected override void ValidateData(
IEntityType entityType,
Dictionary identityMaps,
bool sensitiveDataLogged,
IDiagnosticsLogger logger)
{
if (entityType.IsMappedToJson() && entityType.GetSeedData().Any())
{
throw new InvalidOperationException(RelationalStrings.HasDataNotSupportedForEntitiesMappedToJson(entityType.DisplayName()));
}
foreach (var navigation in entityType.GetNavigations()
.Where(x => x.ForeignKey.IsOwnership && x.TargetEntityType.IsMappedToJson()))
{
if (entityType.GetSeedData().Any(x => x.TryGetValue(navigation.Name, out _)))
{
throw new InvalidOperationException(
RelationalStrings.HasDataNotSupportedForEntitiesMappedToJson(entityType.DisplayName()));
}
}
base.ValidateData(entityType, identityMaps, sensitiveDataLogged, logger);
}
///
protected override void ValidateTrigger(
ITrigger trigger,
IEntityType entityType,
IDiagnosticsLogger logger)
{
base.ValidateTrigger(trigger, entityType, logger);
ValidateTriggerTableMapping(trigger, entityType, logger);
}
///
/// Validates that a trigger is mapped to the same table as its entity type.
///
/// The trigger to validate.
/// The entity type containing the trigger.
/// The logger to use.
protected virtual void ValidateTriggerTableMapping(
ITrigger trigger,
IEntityType entityType,
IDiagnosticsLogger logger)
{
var tableName = entityType.GetTableName();
var tableSchema = entityType.GetSchema();
if ((trigger.GetTableName() != tableName
|| trigger.GetTableSchema() != tableSchema)
&& entityType.GetMappingFragments(StoreObjectType.Table)
.All(f => trigger.GetTableName() != f.StoreObject.Name || trigger.GetTableSchema() != f.StoreObject.Schema))
{
throw new InvalidOperationException(
RelationalStrings.TriggerWithMismatchedTable(
trigger.ModelName,
(trigger.GetTableName()!, trigger.GetTableSchema()).FormatTable(),
entityType.DisplayName(),
entityType.GetSchemaQualifiedTableName())
);
}
}
///
/// Validates the container column type configuration for a specific entity type.
///
/// The entity type to validate.
/// The logger to use.
protected virtual void ValidateContainerColumnType(
IEntityType entityType,
IDiagnosticsLogger logger)
{
if (entityType[RelationalAnnotationNames.ContainerColumnType] != null)
{
if (entityType.FindOwnership()?.PrincipalEntityType.IsOwned() == true)
{
throw new InvalidOperationException(RelationalStrings.ContainerTypeOnNestedOwnedEntityType(entityType.DisplayName()));
}
if (!entityType.IsOwned()
|| entityType.GetContainerColumnName() == null)
{
throw new InvalidOperationException(RelationalStrings.ContainerTypeOnNonContainer(entityType.DisplayName()));
}
}
}
///
/// Validates an owned entity type mapped to a JSON column in a table.
///
/// The entity type to validate.
/// The table identifier.
/// The logger to use.
protected virtual void ValidateJsonOwnedEntityType(
IEntityType entityType,
in StoreObjectIdentifier table,
IDiagnosticsLogger logger)
{
ValidateJsonEntityNavigations(table, entityType);
ValidateJsonEntityKey(table, entityType);
ValidateJsonEntityProperties(table, entityType);
ValidateJsonEntitySingularMapping(table, entityType);
}
///
/// Validates that an entity type owning a JSON entity is mapped to a table or view.
///
/// The entity type to validate.
/// The logger to use.
protected virtual void ValidateJsonEntityOwnerMappedToTableOrView(
IEntityType entityType,
IDiagnosticsLogger logger)
{
if (entityType.GetTableName() != null
|| entityType.GetViewName() != null
|| entityType.IsMappedToJson())
{
return;
}
if (entityType.GetDeclaredNavigations()
.Any(x => x.ForeignKey.IsOwnership && x.TargetEntityType.IsMappedToJson()))
{
throw new InvalidOperationException(
RelationalStrings.JsonEntityWithOwnerNotMappedToTableOrView(
entityType.DisplayName()));
}
}
///
/// Validates the singular (non-collection) mapping aspects of an entity mapped to a JSON column.
///
/// The table identifier.
/// The entity type to validate.
protected virtual void ValidateJsonEntitySingularMapping(
in StoreObjectIdentifier table,
IEntityType jsonEntityType)
{
var ownership = jsonEntityType.FindOwnership()!;
var ownerTableOrViewName = ownership.PrincipalEntityType.GetViewName() ?? ownership.PrincipalEntityType.GetTableName();
if (table.Name != ownerTableOrViewName)
{
throw new InvalidOperationException(
RelationalStrings.JsonEntityMappedToDifferentTableOrViewThanOwner(
jsonEntityType.DisplayName(), table.Name, ownership.PrincipalEntityType.DisplayName(), ownerTableOrViewName));
}
var principalContainerColumn = ownership.PrincipalEntityType.GetContainerColumnName();
if (principalContainerColumn != null
&& principalContainerColumn != jsonEntityType.GetContainerColumnName())
{
throw new InvalidOperationException(
RelationalStrings.JsonEntityMappedToDifferentColumnThanOwner(
jsonEntityType.DisplayName(), jsonEntityType.GetContainerColumnName(),
ownership.PrincipalEntityType.DisplayName(), principalContainerColumn));
}
}
///
/// Validates the JSON entities mapped to a view.
///
/// The entity types mapped to the view.
/// The view identifier.
/// The logger to use.
protected virtual void ValidateJsonView(
IReadOnlyList mappedTypes,
in StoreObjectIdentifier view,
IDiagnosticsLogger logger)
{
foreach (var jsonEntityType in mappedTypes.Where(x => x.IsMappedToJson()))
{
var ownership = jsonEntityType.FindOwnership()!;
var ownerTableOrViewName = ownership.PrincipalEntityType.GetViewName() ?? ownership.PrincipalEntityType.GetTableName();
if (view.Name != ownerTableOrViewName)
{
throw new InvalidOperationException(
RelationalStrings.JsonEntityMappedToDifferentTableOrViewThanOwner(
jsonEntityType.DisplayName(), view.Name, ownership.PrincipalEntityType.DisplayName(), ownerTableOrViewName));
}
}
}
///
/// Validates the root entity mapped to a JSON column.
///
/// The table identifier.
/// The entity type to validate.
protected virtual void ValidateJsonEntityRoot(
in StoreObjectIdentifier table,
IEntityType rootType)
{
var mappingStrategy = rootType.GetMappingStrategy();
if (mappingStrategy is not null and not RelationalAnnotationNames.TphMappingStrategy)
{
// TODO: issue #37445
throw new InvalidOperationException(
RelationalStrings.JsonEntityWithNonTphInheritanceOnOwner(rootType.DisplayName()));
}
}
///
/// Validates navigations of the entity mapped to a JSON column.
///
/// The table identifier.
/// The entity type to validate.
protected virtual void ValidateJsonEntityNavigations(
in StoreObjectIdentifier table,
IEntityType jsonEntityType)
{
var ownership = jsonEntityType.FindOwnership()!;
if (ownership.PrincipalEntityType.IsOwned()
&& !ownership.PrincipalEntityType.IsMappedToJson())
{
//TODO: Allow non-JSON owner, issue #28441
throw new InvalidOperationException(
RelationalStrings.JsonEntityOwnedByNonJsonOwnedType(
ownership.PrincipalEntityType.DisplayName(),
table.DisplayName()));
}
foreach (var navigation in jsonEntityType.GetDeclaredNavigations())
{
if (!navigation.ForeignKey.IsOwnership)
{
throw new InvalidOperationException(
RelationalStrings.JsonEntityReferencingRegularEntity(
jsonEntityType.DisplayName()));
}
}
}
///
/// Validate the key of entity mapped to a JSON column.
///
/// The table identifier.
/// The entity type containing the key to validate.
protected virtual void ValidateJsonEntityKey(
in StoreObjectIdentifier table,
IEntityType jsonEntityType)
{
var primaryKeyProperties = jsonEntityType.FindPrimaryKey()!.Properties;
var ownership = jsonEntityType.FindOwnership()!;
foreach (var primaryKeyProperty in primaryKeyProperties)
{
if (primaryKeyProperty.GetJsonPropertyName() != null)
{
// Issue #28594
throw new InvalidOperationException(
RelationalStrings.JsonEntityWithExplicitlyConfiguredJsonPropertyNameOnKey(
primaryKeyProperty.Name, jsonEntityType.DisplayName()));
}
if (!ownership.IsUnique)
{
// For collection entities, no key properties other than the generated ones are allowed because they
// will not be persisted.
if (!primaryKeyProperty.IsOrdinalKeyProperty()
&& !primaryKeyProperty.IsForeignKey())
{
// issue #28594
throw new InvalidOperationException(
RelationalStrings.JsonEntityWithExplicitlyConfiguredKey(
jsonEntityType.DisplayName(), primaryKeyProperty.Name));
}
}
}
var ownerEntityTypeKeyPropertiesCount = ownership.PrincipalEntityType.FindPrimaryKey()!.Properties.Count;
var expectedKeyCount = ownership.IsUnique
? ownerEntityTypeKeyPropertiesCount
: ownerEntityTypeKeyPropertiesCount + 1;
if (primaryKeyProperties.Count != expectedKeyCount)
{
// issue #28594
throw new InvalidOperationException(
RelationalStrings.JsonEntityWithIncorrectNumberOfKeyProperties(
jsonEntityType.DisplayName(), expectedKeyCount, primaryKeyProperties.Count));
}
}
///
/// Validate the properties of entity mapped to a JSON column.
///
/// The table identifier.
/// The entity type containing the properties to validate.
protected virtual void ValidateJsonEntityProperties(
in StoreObjectIdentifier table,
IEntityType jsonEntityType)
{
var jsonPropertyNames = ValidateJsonProperties(jsonEntityType);
foreach (var navigation in jsonEntityType.GetNavigations())
{
if (!navigation.TargetEntityType.IsMappedToJson()
|| navigation.IsOnDependent)
{
continue;
}
var jsonPropertyName = navigation.TargetEntityType.GetJsonPropertyName();
if (jsonPropertyName != null)
{
CheckUniqueness(jsonPropertyName, navigation.Name, jsonEntityType, jsonPropertyNames);
}
}
}
private static Dictionary ValidateJsonProperties(ITypeBase typeBase)
{
var jsonPropertyNames = new Dictionary();
foreach (var property in typeBase.GetProperties())
{
var jsonPropertyName = property.GetJsonPropertyName();
if (string.IsNullOrEmpty(jsonPropertyName))
{
continue;
}
var columnNameAnnotation = property.FindAnnotation(RelationalAnnotationNames.ColumnName);
if (columnNameAnnotation != null && !string.IsNullOrEmpty((string?)columnNameAnnotation.Value))
{
throw new InvalidOperationException(
RelationalStrings.PropertyBothColumnNameAndJsonPropertyName(
$"{typeBase.DisplayName()}.{property.Name}",
(string)columnNameAnnotation.Value,
jsonPropertyName));
}
if (property.TryGetDefaultValue(out _))
{
// Issue #35934
throw new InvalidOperationException(
RelationalStrings.JsonEntityWithDefaultValueSetOnItsProperty(
typeBase.DisplayName(), property.Name));
}
CheckUniqueness(jsonPropertyName, property.Name, typeBase, jsonPropertyNames);
if (property.IsConcurrencyToken)
{
throw new InvalidOperationException(
RelationalStrings.ConcurrencyTokenOnJsonMappedProperty(
property.Name, typeBase.DisplayName()));
}
}
foreach (var complexProperty in typeBase.GetComplexProperties())
{
var jsonPropertyName = complexProperty.GetJsonPropertyName();
if (jsonPropertyName != null)
{
CheckUniqueness(jsonPropertyName, complexProperty.Name, typeBase, jsonPropertyNames);
}
}
return jsonPropertyNames;
}
private static void CheckUniqueness(
string jsonPropertyName,
string propertyName,
IReadOnlyTypeBase structuralType,
Dictionary jsonPropertyNames)
{
if (jsonPropertyNames.TryGetValue(jsonPropertyName, out var existingProperty))
{
throw new InvalidOperationException(
RelationalStrings.JsonObjectWithMultiplePropertiesMappedToSameJsonProperty(
existingProperty,
propertyName,
structuralType.DisplayName(),
jsonPropertyName));
}
jsonPropertyNames[jsonPropertyName] = propertyName;
}
///
/// Throws an with a message containing provider-specific information, when
/// available, indicating possible reasons why the property cannot be mapped.
///
/// The property CLR type.
/// The structural type.
/// The property.
protected override void ThrowPropertyNotMappedException(
string propertyType,
ITypeBase typeBase,
IProperty unmappedProperty)
{
if (unmappedProperty.ClrType.FullName?.StartsWith("NetTopologySuite.Geometries.", StringComparison.Ordinal) == true
|| typeBase.ClrType.FullName?.StartsWith("NetTopologySuite.Geometries.", StringComparison.Ordinal) == true)
{
throw new InvalidOperationException(
RelationalStrings.PropertyNotMappedSpatial(
propertyType,
typeBase.DisplayName(),
unmappedProperty.Name));
}
var storeType = unmappedProperty.GetColumnType();
if (storeType != null)
{
throw new InvalidOperationException(
RelationalStrings.PropertyNotMapped(
propertyType,
typeBase.DisplayName(),
unmappedProperty.Name,
storeType));
}
base.ThrowPropertyNotMappedException(propertyType, typeBase, unmappedProperty);
}
}