private void ValidateDiscriminator(IEntityType entityType)
 {
     if (entityType.ClrType?.IsInstantiable() ?? false)
     {
         var annotations = _relationalExtensions.For(entityType);
         if (annotations.DiscriminatorProperty == null)
         {
             ShowError(Relational.Internal.Strings.NoDiscriminatorProperty(entityType.DisplayName()));
         }
         if (annotations.DiscriminatorValue == null)
         {
             ShowError(Relational.Internal.Strings.NoDiscriminatorValue(entityType.DisplayName()));
         }
     }
 }
        public virtual InternalEntityEntry StartTracking(
            IEntityType entityType, EntityKey entityKey, object entity, ValueBuffer valueBuffer)
        {
            if (entityKey == EntityKey.InvalidEntityKey)
            {
                throw new InvalidOperationException(Strings.InvalidPrimaryKey(entityType.DisplayName()));
            }

            var existingEntry = TryGetEntry(entityKey);

            if (existingEntry != null)
            {
                if (existingEntry.Entity != entity)
                {
                    throw new InvalidOperationException(Strings.IdentityConflict(entityType.DisplayName()));
                }

                return existingEntry;
            }

            var newEntry = _subscriber.SnapshotAndSubscribe(_factory.Create(this, entityType, entity, valueBuffer));

            _identityMap.Add(entityKey, newEntry);
            _entityReferenceMap[entity] = newEntry;

            newEntry.SetEntityState(EntityState.Unchanged);

            return newEntry;
        }
Esempio n. 3
0
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public virtual EntityProjectionExpression UpdateEntityType([NotNull] IEntityType derivedType)
        {
            Check.NotNull(derivedType, nameof(derivedType));

            if (!derivedType.GetAllBaseTypes().Contains(EntityType))
            {
                throw new InvalidOperationException(
                          CosmosStrings.InvalidDerivedTypeInEntityProjection(
                              derivedType.DisplayName(), EntityType.DisplayName()));
            }

            return(new EntityProjectionExpression(derivedType, AccessExpression));
        }
Esempio n. 4
0
        private void ValidateDiscriminator(IEntityType entityType, ISet <Tuple <IEntityType, string> > discriminatorSet)
        {
            var annotations = new MongoDbEntityTypeAnnotations(entityType);

            if (string.IsNullOrWhiteSpace(annotations.Discriminator))
            {
                ShowError($"Missing discriminator value for entity type {entityType.DisplayName()}.");
            }
            if (!discriminatorSet.Add(Tuple.Create(entityType.RootType(), annotations.Discriminator)))
            {
                ShowError($"Duplicate discriminator value {annotations.Discriminator} for root entity type {entityType.RootType().DisplayName()} (defined on {entityType.DisplayName()}).");
            }
        }
Esempio n. 5
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        protected virtual void ValidateClrInheritance(
            [NotNull] IModel model, [NotNull] IEntityType entityType, [NotNull] HashSet <IEntityType> validEntityTypes)
        {
            Check.NotNull(model, nameof(model));
            Check.NotNull(entityType, nameof(entityType));
            Check.NotNull(validEntityTypes, nameof(validEntityTypes));

            if (validEntityTypes.Contains(entityType))
            {
                return;
            }

            var baseClrType = entityType.ClrType?.GetTypeInfo().BaseType;

            while (baseClrType != null)
            {
                var baseEntityType = model.FindEntityType(baseClrType);
                if (baseEntityType != null)
                {
                    if (!baseEntityType.IsAssignableFrom(entityType))
                    {
                        throw new InvalidOperationException(
                                  CoreStrings.InconsistentInheritance(entityType.DisplayName(), baseEntityType.DisplayName()));
                    }
                    ValidateClrInheritance(model, baseEntityType, validEntityTypes);
                    break;
                }
                baseClrType = baseClrType.GetTypeInfo().BaseType;
            }

            if (entityType.ClrType?.IsInstantiable() == false &&
                !entityType.GetDerivedTypes().Any())
            {
                throw new InvalidOperationException(
                          CoreStrings.AbstractLeafEntityType(entityType.DisplayName()));
            }

            validEntityTypes.Add(entityType);
        }
        public virtual object GetEntity(
            IEntityType entityType,
            EntityKey entityKey,
            EntityLoadInfo entityLoadInfo,
            bool queryStateManager)
        {
            // hot path
            Debug.Assert(entityType != null);
            Debug.Assert(entityKey != null);

            if (entityKey == EntityKey.InvalidEntityKey)
            {
                throw new InvalidOperationException(
                          Strings.InvalidEntityKeyOnQuery(entityType.DisplayName()));
            }

            if (queryStateManager)
            {
                var entry = _stateManager.TryGetEntry(entityKey);

                if (entry != null)
                {
                    return(entry.Entity);
                }
            }

            object entity;

            WeakReference <object> weakReference;

            if (!_identityMap.TryGetValue(entityKey, out weakReference) ||
                !weakReference.TryGetTarget(out entity))
            {
                entity = entityLoadInfo.Materialize();

                if (weakReference != null)
                {
                    weakReference.SetTarget(entity);
                }
                else
                {
                    GarbageCollectIdentityMap();

                    _identityMap.Add(entityKey, new WeakReference <object>(entity));
                }

                _valueBuffers.Add(entity, entityLoadInfo.ValueBuffer);
            }

            return(entity);
        }
Esempio n. 7
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public static IEnumerable <INavigation> FindNavigationsToInHierarchy(
            [NotNull] this IForeignKey foreignKey, [NotNull] IEntityType entityType)
        {
            if (!foreignKey.DeclaringEntityType.IsAssignableFrom(entityType) &&
                !foreignKey.PrincipalEntityType.IsAssignableFrom(entityType))
            {
                throw new InvalidOperationException(CoreStrings.EntityTypeNotInRelationship(
                                                        entityType.DisplayName(), foreignKey.DeclaringEntityType.DisplayName(), foreignKey.PrincipalEntityType.DisplayName()));
            }

            return(foreignKey.IsIntraHierarchical()
                ? foreignKey.GetNavigations()
                : foreignKey.FindNavigations(foreignKey.PrincipalEntityType.IsAssignableFrom(entityType)));
        }
Esempio n. 8
0
        private static INotifyPropertyChanging AsINotifyPropertyChanging(
            InternalEntityEntry entry,
            IEntityType entityType,
            ChangeTrackingStrategy changeTrackingStrategy)
        {
            if (!(entry.Entity is INotifyPropertyChanging changing))
            {
                throw new InvalidOperationException(
                          CoreStrings.ChangeTrackingInterfaceMissing(
                              entityType.DisplayName(), changeTrackingStrategy, nameof(INotifyPropertyChanging)));
            }

            return(changing);
        }
Esempio n. 9
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public static IEntityType ResolveEntityTypeInHierarchy([NotNull] this IForeignKey foreignKey, [NotNull] IEntityType entityType)
        {
            if (!foreignKey.DeclaringEntityType.IsAssignableFrom(entityType) &&
                !foreignKey.PrincipalEntityType.IsAssignableFrom(entityType))
            {
                throw new InvalidOperationException(CoreStrings.EntityTypeNotInRelationship(
                                                        entityType.DisplayName(),
                                                        foreignKey.DeclaringEntityType.DisplayName(),
                                                        foreignKey.PrincipalEntityType.DisplayName()));
            }

            if (foreignKey.IsIntraHierarchical())
            {
                throw new InvalidOperationException(CoreStrings.IntraHierarchicalAmbiguousTargetEntityType(
                                                        entityType.DisplayName(), Property.Format(foreignKey.Properties),
                                                        foreignKey.PrincipalEntityType.DisplayName(),
                                                        foreignKey.DeclaringEntityType.DisplayName()));
            }

            return(foreignKey.DeclaringEntityType.IsAssignableFrom(entityType)
                ? foreignKey.DeclaringEntityType
                : foreignKey.PrincipalEntityType);
        }
Esempio n. 10
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public static MemberInfo GetNavigationMemberInfo(
            [NotNull] this IEntityType entityType,
            [NotNull] string navigationName)
        {
            var memberInfo = entityType.ClrType.GetMembersInHierarchy(navigationName).FirstOrDefault();

            if (memberInfo == null)
            {
                throw new InvalidOperationException(
                          CoreStrings.NoClrNavigation(navigationName, entityType.DisplayName()));
            }

            return(memberInfo);
        }
        private static INotifyCollectionChanged AsINotifyCollectionChanged(
            InternalEntityEntry entry,
            INavigation navigation,
            IEntityType entityType,
            ChangeTrackingStrategy changeTrackingStrategy)
        {
            if (!(navigation.GetCollectionAccessor()?.GetOrCreate(entry.Entity) is INotifyCollectionChanged notifyingCollection))
            {
                throw new InvalidOperationException(
                          CoreStrings.NonNotifyingCollection(navigation.Name, entityType.DisplayName(), changeTrackingStrategy));
            }

            return(notifyingCollection);
        }
Esempio n. 12
0
        public virtual object GetEntity(
            IEntityType entityType,
            EntityKey entityKey,
            EntityLoadInfo entityLoadInfo,
            bool queryStateManager)
        {
            // hot path
            Debug.Assert(entityType != null);
            Debug.Assert(entityKey != null);

            if (entityKey == EntityKey.InvalidEntityKey)
            {
                throw new InvalidOperationException(
                    Strings.InvalidEntityKeyOnQuery(entityType.DisplayName()));
            }

            if (queryStateManager)
            {
                var entry = _stateManager.TryGetEntry(entityKey);

                if (entry != null)
                {
                    return entry.Entity;
                }
            }

            object entity;

            WeakReference<object> weakReference;
            if (!_identityMap.TryGetValue(entityKey, out weakReference)
                || !weakReference.TryGetTarget(out entity))
            {
                entity = entityLoadInfo.Materialize();

                if (weakReference != null)
                {
                    weakReference.SetTarget(entity);
                }
                else
                {
                    GarbageCollectIdentityMap();

                    _identityMap.Add(entityKey, new WeakReference<object>(entity));
                }

                _valueBuffers.Add(entity, entityLoadInfo.ValueBuffer);
            }

            return entity;
        }
Esempio n. 13
0
        protected virtual void GenerateTableName([NotNull] IEntityType entityType, [NotNull] IndentedStringBuilder stringBuilder)
        {
            Check.NotNull(entityType, nameof(entityType));
            Check.NotNull(stringBuilder, nameof(stringBuilder));

            if (entityType.FindAnnotation(RelationalAnnotationNames.Prefix + RelationalAnnotationNames.TableName) == null &&
                entityType.HasClrType())
            {
                stringBuilder
                .AppendLine()
                .Append("b.ToTable(")
                .Append(_code.Literal(entityType.DisplayName()))
                .AppendLine(");");
            }
        }
Esempio n. 14
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public static IEntityType ResolveOtherEntityType([NotNull] this IForeignKey foreignKey, [NotNull] IEntityType entityType)
        {
            if (foreignKey.DeclaringEntityType != entityType &&
                foreignKey.PrincipalEntityType != entityType)
            {
                throw new InvalidOperationException(CoreStrings.EntityTypeNotInRelationshipStrict(
                                                        entityType.DisplayName(),
                                                        foreignKey.DeclaringEntityType.DisplayName(),
                                                        foreignKey.PrincipalEntityType.DisplayName()));
            }

            return(foreignKey.DeclaringEntityType == entityType
                ? foreignKey.PrincipalEntityType
                : foreignKey.DeclaringEntityType);
        }
Esempio n. 15
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public static IEnumerable <INavigation> FindNavigationsTo([NotNull] this IForeignKey foreignKey, [NotNull] IEntityType entityType)
        {
            if (foreignKey.DeclaringEntityType != entityType &&
                foreignKey.PrincipalEntityType != entityType)
            {
                throw new InvalidOperationException(CoreStrings.EntityTypeNotInRelationshipStrict(
                                                        entityType.DisplayName(),
                                                        foreignKey.DeclaringEntityType.DisplayName(),
                                                        foreignKey.PrincipalEntityType.DisplayName()));
            }

            return(foreignKey.IsSelfReferencing()
                ? foreignKey.GetNavigations()
                : foreignKey.FindNavigations(foreignKey.PrincipalEntityType == entityType));
        }
Esempio n. 16
0
        private static INotifyPropertyChanged AsINotifyPropertyChanged(
            InternalEntityEntry entry,
            IEntityType entityType,
            ChangeTrackingStrategy changeTrackingStrategy)
        {
            var changed = entry.Entity as INotifyPropertyChanged;

            if (changed == null)
            {
                throw new InvalidOperationException(
                          CoreStrings.ChangeTrackingInterfaceMissing(
                              entityType.DisplayName(), changeTrackingStrategy, nameof(INotifyPropertyChanged)));
            }

            return(changed);
        }
Esempio n. 17
0
        private static void CheckDiscriminatorValue(IEntityType entityType, object value)
        {
            if (value != null &&
                entityType.GetDiscriminatorProperty() == null)
            {
                throw new InvalidOperationException(
                          RelationalStrings.NoDiscriminatorForValue(entityType.DisplayName(), entityType.RootType().DisplayName()));
            }

            if (value != null &&
                !entityType.GetDiscriminatorProperty().ClrType.GetTypeInfo().IsAssignableFrom(value.GetType().GetTypeInfo()))
            {
                throw new InvalidOperationException(
                          RelationalStrings.DiscriminatorValueIncompatible(
                              value, entityType.GetDiscriminatorProperty().Name, entityType.GetDiscriminatorProperty().ClrType));
            }
        }
Esempio n. 18
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public static void SchemaConfiguredWarning(
            this IDiagnosticsLogger <DbLoggerCategory.Model.Validation> diagnostics,
            IEntityType entityType,
            string schema)
        {
            var definition = FbStrings.LogSchemaConfigured;

            var warningBehavior = definition.GetLogBehavior(diagnostics);

            if (warningBehavior != WarningBehavior.Ignore)
            {
                definition.Log(
                    diagnostics,
                    warningBehavior,
                    entityType.DisplayName(), schema);
            }
        }
Esempio n. 19
0
        private static void CheckDiscriminatorProperty(IEntityType entityType, IProperty property)
        {
            if (property != null)
            {
                if (entityType != entityType.RootType())
                {
                    throw new InvalidOperationException(
                              RelationalStrings.DiscriminatorPropertyMustBeOnRoot(entityType.DisplayName()));
                }

                if (property.DeclaringEntityType != entityType)
                {
                    throw new InvalidOperationException(
                              RelationalStrings.DiscriminatorPropertyNotFound(property.Name, entityType.DisplayName()));
                }
            }
        }
    private static INotifyCollectionChanged AsINotifyCollectionChanged(
        InternalEntityEntry entry,
        INavigationBase navigation,
        IEntityType entityType,
        ChangeTrackingStrategy changeTrackingStrategy)
    {
        if (navigation.GetCollectionAccessor()
            ?.GetOrCreate(entry.Entity, forMaterialization: false) is not INotifyCollectionChanged notifyingCollection)
        {
            var collectionType = navigation.GetCollectionAccessor()
                                 ?.GetOrCreate(entry.Entity, forMaterialization: false).GetType().DisplayName(fullName: false);
            throw new InvalidOperationException(
                      CoreStrings.NonNotifyingCollection(navigation.Name, entityType.DisplayName(), collectionType, changeTrackingStrategy));
        }

        return(notifyingCollection);
    }
        private Shaper CreateShaper(Type elementType, IEntityType entityType, SelectExpression selectExpression)
        {
            Shaper shaper;

            if (QueryModelVisitor.QueryCompilationContext
                .QuerySourceRequiresMaterialization(_querySource) ||
                QueryModelVisitor.RequiresClientEval)
            {
                Dictionary <Type, int[]> typeIndexMap;

                var materializer
                    = _materializerFactory
                      .CreateMaterializer(
                          entityType,
                          selectExpression,
                          (p, se) =>
                          se.AddToProjection(
                              _relationalAnnotationProvider.For(p).ColumnName,
                              p,
                              _querySource),
                          _querySource,
                          out typeIndexMap).Compile();

                shaper
                    = (Shaper)_createEntityShaperMethodInfo.MakeGenericMethod(elementType)
                      .Invoke(null, new object[]
                {
                    _querySource,
                    entityType.DisplayName(),
                    QueryModelVisitor.QueryCompilationContext.IsTrackingQuery,
                    entityType.FindPrimaryKey(),
                    materializer,
                    typeIndexMap,
                    QueryModelVisitor.QueryCompilationContext.IsQueryBufferRequired
                });
            }
            else
            {
                DiscriminateProjectionQuery(entityType, selectExpression, _querySource);

                shaper = new ValueBufferShaper(_querySource);
            }

            return(shaper);
        }
Esempio n. 22
0
        public static IEnumerable <INavigation> FindNavigationsTo([NotNull] this IForeignKey foreignKey, [NotNull] IEntityType entityType)
        {
            Check.NotNull(foreignKey, nameof(foreignKey));
            Check.NotNull(entityType, nameof(entityType));

            if ((foreignKey.DeclaringEntityType != entityType) &&
                (foreignKey.PrincipalEntityType != entityType))
            {
                throw new ArgumentException(CoreStrings.EntityTypeNotInRelationshipStrict(
                                                entityType.DisplayName(),
                                                foreignKey.DeclaringEntityType.DisplayName(),
                                                foreignKey.PrincipalEntityType.DisplayName()));
            }

            return(foreignKey.IsSelfReferencing()
                ? foreignKey.GetNavigations()
                : foreignKey.FindNavigations(foreignKey.PrincipalEntityType == entityType));
        }
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public static IProperty GetProperty([NotNull] this IEntityType entityType, [NotNull] string name)
        {
            Check.NotEmpty(name, nameof(name));

            var property = entityType.FindProperty(name);

            if (property == null)
            {
                if (entityType.FindNavigation(name) != null)
                {
                    throw new InvalidOperationException(
                              CoreStrings.PropertyIsNavigation(name, entityType.DisplayName(),
                                                               nameof(EntityEntry.Property), nameof(EntityEntry.Reference), nameof(EntityEntry.Collection)));
                }
                throw new InvalidOperationException(CoreStrings.PropertyNotFound(name, entityType.DisplayName()));
            }
            return(property);
        }
Esempio n. 24
0
        public static IEntityType ResolveOtherEntityType([NotNull] this IForeignKey foreignKey, [NotNull] IEntityType entityType)
        {
            Check.NotNull(foreignKey, nameof(foreignKey));
            Check.NotNull(entityType, nameof(entityType));

            if (foreignKey.DeclaringEntityType != entityType &&
                foreignKey.PrincipalEntityType != entityType)
            {
                throw new ArgumentException(CoreStrings.EntityTypeNotInRelationshipStrict(
                                                entityType.DisplayName(),
                                                foreignKey.DeclaringEntityType.DisplayName(),
                                                foreignKey.PrincipalEntityType.DisplayName()));
            }

            return(foreignKey.DeclaringEntityType == entityType
                ? foreignKey.PrincipalEntityType
                : foreignKey.DeclaringEntityType);
        }
Esempio n. 25
0
        private static TEntity CreateEntity <TEntity>(
            IQuerySource querySource,
            ValueBuffer valueBuffer,
            int valueBufferOffset,
            QueryContext queryContext,
            IEntityType entityType,
            bool trackingQuery,
            KeyValueFactory keyValueFactory,
            Func <ValueBuffer, object> materializer,
            bool allowNullResult,
            bool useQueryBuffer)
            where TEntity : class
        {
            valueBuffer = valueBuffer.WithOffset(valueBufferOffset);

            var keyValue = keyValueFactory.Create(valueBuffer);

            TEntity entity = null;

            if (ReferenceEquals(keyValue, KeyValue.InvalidKeyValue))
            {
                if (!allowNullResult)
                {
                    throw new InvalidOperationException(
                              RelationalStrings.InvalidKeyValue(entityType.DisplayName()));
                }
            }
            else if (useQueryBuffer)
            {
                entity
                    = (TEntity)queryContext.QueryBuffer
                      .GetEntity(
                          keyValue,
                          new EntityLoadInfo(valueBuffer, materializer),
                          queryStateManager: trackingQuery);
            }
            else
            {
                entity = (TEntity)materializer(valueBuffer);
            }

            return(entity);
        }
Esempio n. 26
0
    /// <summary>
    ///     Validates the discriminator and values for all entity types derived from the given one.
    /// </summary>
    /// <param name="rootEntityType">The entity type to validate.</param>
    protected virtual void ValidateDiscriminatorValues(IEntityType rootEntityType)
    {
        var derivedTypes = rootEntityType.GetDerivedTypesInclusive().ToList();

        if (derivedTypes.Count == 1)
        {
            return;
        }

        var discriminatorProperty = rootEntityType.FindDiscriminatorProperty();

        if (discriminatorProperty == null)
        {
            throw new InvalidOperationException(
                      CoreStrings.NoDiscriminatorProperty(rootEntityType.DisplayName()));
        }

        var discriminatorValues = new Dictionary <object, IEntityType>(discriminatorProperty.GetKeyValueComparer());

        foreach (var derivedType in derivedTypes)
        {
            if (!derivedType.ClrType.IsInstantiable())
            {
                continue;
            }

            var discriminatorValue = derivedType.GetDiscriminatorValue();
            if (discriminatorValue == null)
            {
                throw new InvalidOperationException(
                          CoreStrings.NoDiscriminatorValue(derivedType.DisplayName()));
            }

            if (discriminatorValues.TryGetValue(discriminatorValue, out var duplicateEntityType))
            {
                throw new InvalidOperationException(
                          CoreStrings.DuplicateDiscriminatorValue(
                              derivedType.DisplayName(), discriminatorValue, duplicateEntityType.DisplayName()));
            }

            discriminatorValues[discriminatorValue] = derivedType;
        }
    }
Esempio n. 27
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public static void DuplicateDependentEntityTypeInstanceWarning(
            [NotNull] this IDiagnosticsLogger <DbLoggerCategory.Update> diagnostics,
            [NotNull] IEntityType dependent1,
            [NotNull] IEntityType dependent2)
        {
            var definition = CoreStrings.LogDuplicateDependentEntityTypeInstance;

            definition.Log(diagnostics, dependent1.DisplayName(), dependent2.DisplayName());

            if (diagnostics.DiagnosticSource.IsEnabled(definition.EventId.Name))
            {
                diagnostics.DiagnosticSource.Write(
                    definition.EventId.Name,
                    new SharedDependentEntityEventData(
                        definition,
                        DuplicateDependentEntityTypeInstanceWarning,
                        dependent1,
                        dependent2));
            }
        }
Esempio n. 28
0
        public virtual string GenerateTableNameFacetConfiguration([NotNull] IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            if (entityType.Relational().Schema != null &&
                entityType.Relational().Schema != "dbo")
            {
                return(string.Format(CultureInfo.InvariantCulture, ".Table({0}, {1})",
                                     CSharpUtilities.Instance.DelimitString(entityType.Relational().Table),
                                     CSharpUtilities.Instance.DelimitString(entityType.Relational().Schema)));
            }

            if (entityType.Relational().Table != null &&
                entityType.Relational().Table != entityType.DisplayName())
            {
                return(string.Format(CultureInfo.InvariantCulture, ".Table({0})",
                                     CSharpUtilities.Instance.DelimitString(entityType.Relational().Table)));
            }

            return(null);
        }
Esempio n. 29
0
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public virtual EntityProjectionExpression UpdateEntityType([NotNull] IEntityType derivedType)
        {
            if (!derivedType.GetAllBaseTypes().Contains(EntityType))
            {
                throw new InvalidOperationException(InMemoryStrings.InvalidDerivedTypeInEntityProjection(
                                                        derivedType.DisplayName(), EntityType.DisplayName()));
            }

            var readExpressionMap = new Dictionary <IProperty, Expression>();

            foreach (var kvp in _readExpressionMap)
            {
                var property = kvp.Key;
                if (derivedType.IsAssignableFrom(property.DeclaringEntityType) ||
                    property.DeclaringEntityType.IsAssignableFrom(derivedType))
                {
                    readExpressionMap[property] = kvp.Value;
                }
            }

            return(new EntityProjectionExpression(derivedType, readExpressionMap));
        }
        public static void SchemaConfiguredWarning(
            [NotNull] this IDiagnosticsLogger <DbLoggerCategory.Model.Validation> diagnostics,
            [NotNull] IEntityType entityType,
            [NotNull] string schema)
        {
            var definition = EFCoreStrings.LogSchemaConfigured;

            // Checking for enabled here to avoid string formatting if not needed.
            if (diagnostics.GetLogBehavior(definition.EventId, definition.Level) != WarningBehavior.Ignore)
            {
                definition.Log(diagnostics, entityType.DisplayName(), schema);
            }
            if (diagnostics.DiagnosticSource.IsEnabled(definition.EventId.Name))
            {
                diagnostics.DiagnosticSource.Write(
                    definition.EventId.Name,
                    new EntityTypeSchemaEventData(
                        definition,
                        SchemaConfiguredWarning,
                        entityType,
                        schema));
            }
        }
Esempio n. 31
0
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public static void SchemaConfiguredWarning(
            [NotNull] this IDiagnosticsLogger <DbLoggerCategory.Model.Validation> diagnostics,
            [NotNull] IEntityType entityType,
            [NotNull] string schema)
        {
            var definition = SqliteResources.LogSchemaConfigured(diagnostics);

            if (diagnostics.ShouldLog(definition))
            {
                definition.Log(diagnostics, entityType.DisplayName(), schema);
            }

            if (diagnostics.NeedsEventData(definition, out var diagnosticSourceEnabled, out var simpleLogEnabled))
            {
                var eventData = new EntityTypeSchemaEventData(
                    definition,
                    SchemaConfiguredWarning,
                    entityType,
                    schema);

                diagnostics.DispatchEventData(definition, eventData, diagnosticSourceEnabled, simpleLogEnabled);
            }
        }
Esempio n. 32
0
        public virtual EntityProjectionExpression UpdateEntityType([NotNull] IEntityType derivedType)
        {
            Check.NotNull(derivedType, nameof(derivedType));

            if (!derivedType.GetAllBaseTypes().Contains(EntityType))
            {
                throw new InvalidOperationException(
                          RelationalStrings.InvalidDerivedTypeInEntityProjection(
                              derivedType.DisplayName(), EntityType.DisplayName()));
            }

            var propertyExpressionMap = new Dictionary <IProperty, ColumnExpression>();

            foreach (var kvp in _propertyExpressionMap)
            {
                var property = kvp.Key;
                if (derivedType.IsAssignableFrom(property.DeclaringEntityType) ||
                    property.DeclaringEntityType.IsAssignableFrom(derivedType))
                {
                    propertyExpressionMap[property] = kvp.Value;
                }
            }

            var discriminatorExpression = DiscriminatorExpression;

            if (DiscriminatorExpression is CaseExpression caseExpression)
            {
                var entityTypesToSelect = derivedType.GetTptDiscriminatorValues();
                var whenClauses         = caseExpression.WhenClauses
                                          .Where(wc => entityTypesToSelect.Contains((string)((SqlConstantExpression)wc.Result).Value !))
                                          .ToList();

                discriminatorExpression = caseExpression.Update(operand: null, whenClauses, elseResult: null);
            }

            return(new EntityProjectionExpression(derivedType, propertyExpressionMap, discriminatorExpression));
        }
 public virtual string CreateName(IEntityType entityType)
     => _shouldPluralize ? entityType.DisplayName().Pluralize() : entityType.DisplayName();
        private static INotifyPropertyChanging AsINotifyPropertyChanging(
            InternalEntityEntry entry,
            IEntityType entityType,
            ChangeTrackingStrategy changeTrackingStrategy)
        {
            var changing = entry.Entity as INotifyPropertyChanging;
            if (changing == null)
            {
                throw new InvalidOperationException(
                    CoreStrings.ChangeTrackingInterfaceMissing(
                        entityType.DisplayName(), changeTrackingStrategy, typeof(INotifyPropertyChanging).Name));
            }

            return changing;
        }
        private static INotifyCollectionChanged AsINotifyCollectionChanged(
            InternalEntityEntry entry,
            INavigation navigation,
            IEntityType entityType,
            ChangeTrackingStrategy changeTrackingStrategy)
        {
            var notifyingCollection = navigation.GetCollectionAccessor().GetOrCreate(entry.Entity) as INotifyCollectionChanged;
            if (notifyingCollection == null)
            {
                throw new InvalidOperationException(
                    CoreStrings.NonNotifyingCollection(navigation.Name, entityType.DisplayName(), changeTrackingStrategy));
            }

            return notifyingCollection;
        }
Esempio n. 36
0
        public virtual InternalEntityEntry StartTracking(IEntityType entityType, object entity, IValueReader valueReader)
        {
            // TODO: Perf: Pre-compute this for speed
            var keyProperties = entityType.GetPrimaryKey().Properties;
            var keyValue = _keyFactorySource.GetKeyFactory(keyProperties).Create(entityType, keyProperties, valueReader);

            if (keyValue == EntityKey.InvalidEntityKey)
            {
                throw new InvalidOperationException(Strings.InvalidPrimaryKey(entityType.DisplayName()));
            }

            var existingEntry = TryGetEntry(keyValue);

            if (existingEntry != null)
            {
                if (existingEntry.Entity != entity)
                {
                    throw new InvalidOperationException(Strings.IdentityConflict(entityType.DisplayName()));
                }

                return existingEntry;
            }

            var newEntry = _subscriber.SnapshotAndSubscribe(_factory.Create(this, entityType, entity, valueReader));

            _identityMap.Add(keyValue, newEntry);
            _entityReferenceMap[entity] = newEntry;

            newEntry.SetEntityState(EntityState.Unchanged);

            return newEntry;
        }
 private void ValidateDiscriminator(IEntityType entityType)
 {
     var annotations = RelationalExtensions.For(entityType);
     if (annotations.DiscriminatorProperty == null)
     {
         ShowError(RelationalStrings.NoDiscriminatorProperty(entityType.DisplayName()));
     }
     if (annotations.DiscriminatorValue == null)
     {
         ShowError(RelationalStrings.NoDiscriminatorValue(entityType.DisplayName()));
     }
 }
Esempio n. 38
0
        private void EnsureClrInheritance(IModel model, IEntityType entityType, HashSet<IEntityType> validEntityTypes)
        {
            if (validEntityTypes.Contains(entityType))
            {
                return;
            }

            var baseClrType = entityType.ClrType?.GetTypeInfo().BaseType;
            while (baseClrType != null)
            {
                var baseEntityType = model.FindEntityType(baseClrType);
                if (baseEntityType != null)
                {
                    if (!baseEntityType.IsAssignableFrom(entityType))
                    {
                        ShowError(CoreStrings.InconsistentInheritance(entityType.DisplayName(), baseEntityType.DisplayName()));
                    }
                    EnsureClrInheritance(model, baseEntityType, validEntityTypes);
                    break;
                }
                baseClrType = baseClrType.GetTypeInfo().BaseType;
            }

            if (entityType.ClrType?.IsInstantiable() == false
                && !entityType.GetDerivedTypes().Any())
            {
                ShowError(CoreStrings.AbstractLeafEntityType(entityType.DisplayName()));
            }

            validEntityTypes.Add(entityType);
        }
Esempio n. 39
0
        public virtual InternalEntityEntry StartTracking(
            IEntityType entityType, IKeyValue keyValue, object entity, ValueBuffer valueBuffer)
        {
            if (keyValue == KeyValue.InvalidKeyValue)
            {
                throw new InvalidOperationException(CoreStrings.InvalidPrimaryKey(entityType.DisplayName()));
            }

            var existingEntry = TryGetEntry(keyValue);
            if (existingEntry != null)
            {
                if (existingEntry.Entity != entity)
                {
                    throw new InvalidOperationException(CoreStrings.IdentityConflict(entityType.DisplayName()));
                }

                return existingEntry;
            }

            var newEntry = _subscriber.SnapshotAndSubscribe(_factory.Create(this, entityType, entity, valueBuffer), valueBuffer);

            AddToIdentityMap(entityType, keyValue, newEntry);

            _entityReferenceMap[entity] = newEntry;
            _detachedEntityReferenceMap.Remove(entity);

            newEntry.SetEntityState(EntityState.Unchanged);

            return newEntry;
        }
Esempio n. 40
0
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        protected virtual void ValidateSharedContainerCompatibility(
            [NotNull] IReadOnlyList <IEntityType> mappedTypes,
            [NotNull] string container,
            [NotNull] IDiagnosticsLogger <DbLoggerCategory.Model.Validation> logger)
        {
            var         discriminatorValues = new Dictionary <object, IEntityType>();
            IProperty   partitionKey        = null;
            IEntityType firstEntityType     = null;

            foreach (var entityType in mappedTypes)
            {
                Check.DebugAssert(entityType.IsDocumentRoot(), "Only document roots expected here.");
                var partitionKeyPropertyName = entityType.GetPartitionKeyPropertyName();
                if (partitionKeyPropertyName != null)
                {
                    var nextPartitionKeyProperty = entityType.FindProperty(partitionKeyPropertyName);
                    if (partitionKey == null)
                    {
                        if (firstEntityType != null)
                        {
                            throw new InvalidOperationException(CosmosStrings.NoPartitionKey(firstEntityType.DisplayName(), container));
                        }

                        partitionKey = nextPartitionKeyProperty;
                    }
                    else if (partitionKey.GetJsonPropertyName() != nextPartitionKeyProperty.GetJsonPropertyName())
                    {
                        throw new InvalidOperationException(
                                  CosmosStrings.PartitionKeyStoreNameMismatch(
                                      partitionKey.Name, firstEntityType.DisplayName(), partitionKey.GetJsonPropertyName(),
                                      nextPartitionKeyProperty.Name, entityType.DisplayName(), nextPartitionKeyProperty.GetJsonPropertyName()));
                    }
                }
                else if (partitionKey != null)
                {
                    throw new InvalidOperationException(CosmosStrings.NoPartitionKey(entityType.DisplayName(), container));
                }

                if (mappedTypes.Count == 1)
                {
                    break;
                }

                if (firstEntityType == null)
                {
                    firstEntityType = entityType;
                }

                if (entityType.ClrType?.IsInstantiable() == true &&
                    entityType.GetContainingPropertyName() == null)
                {
                    if (entityType.GetDiscriminatorProperty() == null)
                    {
                        throw new InvalidOperationException(
                                  CosmosStrings.NoDiscriminatorProperty(entityType.DisplayName(), container));
                    }

                    var discriminatorValue = entityType.GetDiscriminatorValue();
                    if (discriminatorValue == null)
                    {
                        throw new InvalidOperationException(
                                  CosmosStrings.NoDiscriminatorValue(entityType.DisplayName(), container));
                    }

                    if (discriminatorValues.TryGetValue(discriminatorValue, out var duplicateEntityType))
                    {
                        throw new InvalidOperationException(
                                  CosmosStrings.DuplicateDiscriminatorValue(
                                      entityType.DisplayName(), discriminatorValue, duplicateEntityType.DisplayName(), container));
                    }

                    discriminatorValues[discriminatorValue] = entityType;
                }
            }
        }
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used 
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual Expression CreateMaterializeExpression(
            IEntityType entityType,
            Expression valueBufferExpression,
            int[] indexMap = null)
        {
            // ReSharper disable once SuspiciousTypeConversion.Global
            var materializer = entityType as IEntityMaterializer;

            if (materializer != null)
            {
                return Expression.Call(
                    Expression.Constant(materializer),
                    ((Func<ValueBuffer, object>)materializer.CreateEntity).GetMethodInfo(),
                    valueBufferExpression);
            }

            if (!entityType.HasClrType())
            {
                throw new InvalidOperationException(CoreStrings.NoClrType(entityType.Name));
            }

            if (entityType.IsAbstract())
            {
                throw new InvalidOperationException(CoreStrings.CannotMaterializeAbstractType(entityType));
            }

            var constructorInfo = entityType.ClrType.GetDeclaredConstructor(null);

            if (constructorInfo == null)
            {
                throw new InvalidOperationException(CoreStrings.NoParameterlessConstructor(entityType.DisplayName()));
            }

            var instanceVariable = Expression.Variable(entityType.ClrType, "instance");

            var blockExpressions
                = new List<Expression>
                {
                    Expression.Assign(
                        instanceVariable,
                        Expression.New(constructorInfo))
                };

            blockExpressions.AddRange(
                from mapping in _memberMapper.MapPropertiesToMembers(entityType)
                let propertyInfo = mapping.Item2 as PropertyInfo
                let targetMember
                    = propertyInfo != null
                        ? Expression.Property(instanceVariable, propertyInfo)
                        : Expression.Field(instanceVariable, (FieldInfo)mapping.Item2)
                select
                    Expression.Assign(
                        targetMember,
                        CreateReadValueExpression(
                            valueBufferExpression,
                            targetMember.Type,
                            indexMap?[mapping.Item1.GetIndex()] ?? mapping.Item1.GetIndex())));

            blockExpressions.Add(instanceVariable);

            return Expression.Block(new[] { instanceVariable }, blockExpressions);
        }