Ejemplo n.º 1
0
 public static Dictionary <string, object> GetStorageParameters([NotNull] this IReadOnlyEntityType entityType)
 => entityType.GetAnnotations()
 .Where(a => a.Name.StartsWith(NpgsqlAnnotationNames.StorageParameterPrefix))
 .ToDictionary(
     a => a.Name.Substring(NpgsqlAnnotationNames.StorageParameterPrefix.Length),
     a => a.Value
     );
 public static Dictionary <string, object?> GetStorageParameters(this IReadOnlyEntityType entityType)
 => entityType.GetAnnotations()
 .Where(a => a.Name.StartsWith(NpgsqlAnnotationNames.StorageParameterPrefix, StringComparison.Ordinal))
 .ToDictionary(
     a => a.Name.Substring(NpgsqlAnnotationNames.StorageParameterPrefix.Length),
     a => a.Value
     );
 /// <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 ParameterBinding Bind(
     IReadOnlyEntityType entityType,
     Type parameterType,
     string parameterName)
 => new ContextParameterBinding(
     parameterType,
     entityType.GetServiceProperties().Cast <IPropertyBase>().Where(p => p.ClrType == parameterType).ToArray());
 public virtual ParameterBinding Bind(
     IReadOnlyEntityType entityType,
     Type parameterType,
     string parameterName)
 => new ContextParameterBinding(
     parameterType,
     (IPropertyBase?)entityType.GetServiceProperties().FirstOrDefault(p => p.ClrType == parameterType));
Ejemplo n.º 5
0
        private bool TryBindConstructor(
            IReadOnlyEntityType entityType,
            ConstructorInfo constructor,
            Func<IParameterBindingFactory?, IReadOnlyEntityType, Type, string, ParameterBinding?> bind,
            [CA.NotNullWhen(true)] out InstantiationBinding? binding,
            [CA.NotNullWhen(false)] out IEnumerable<ParameterInfo>? unboundParameters)
        {
            IEnumerable<(ParameterInfo Parameter, ParameterBinding? Binding)> bindings
                = constructor.GetParameters().Select(
                        p => (p, string.IsNullOrEmpty(p.Name)
                            ? null
                            : _propertyFactory.FindParameter((IEntityType)entityType, p.ParameterType, p.Name)
                            ?? bind(_factories.FindFactory(p.ParameterType, p.Name), entityType, p.ParameterType, p.Name)))
                    .ToList();

            if (bindings.Any(b => b.Binding == null))
            {
                unboundParameters = bindings.Where(b => b.Binding == null).Select(b => b.Parameter);
                binding = null;

                return false;
            }

            unboundParameters = null;
            binding = new ConstructorBinding(constructor, bindings.Select(b => b.Binding).ToList()!);

            return true;
        }
Ejemplo n.º 6
0
        public static bool UseEagerSnapshots([NotNull] this IReadOnlyEntityType entityType)
        {
            var changeTrackingStrategy = entityType.GetChangeTrackingStrategy();

            return(changeTrackingStrategy == ChangeTrackingStrategy.Snapshot ||
                   changeTrackingStrategy == ChangeTrackingStrategy.ChangedNotifications);
        }
Ejemplo n.º 7
0
        public static bool IsStrictlyDerivedFrom([NotNull] this IReadOnlyEntityType entityType, [NotNull] IReadOnlyEntityType baseType)
        {
            Check.NotNull(entityType, nameof(entityType));
            Check.NotNull(baseType, nameof(baseType));

            return(entityType == baseType ? false : baseType.IsAssignableFrom(entityType));
        }
Ejemplo n.º 8
0
        public static IReadOnlyEntityType ResolveEntityTypeInHierarchy(
            this IReadOnlyForeignKey foreignKey, IReadOnlyEntityType 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.DeclaringEntityType.IsAssignableFrom(foreignKey.PrincipalEntityType) ||
                foreignKey.PrincipalEntityType.IsAssignableFrom(foreignKey.DeclaringEntityType))
            {
                throw new InvalidOperationException(
                          CoreStrings.IntraHierarchicalAmbiguousTargetEntityType(
                              entityType.DisplayName(), foreignKey.Properties.Format(),
                              foreignKey.PrincipalEntityType.DisplayName(),
                              foreignKey.DeclaringEntityType.DisplayName()));
            }

            return(foreignKey.DeclaringEntityType.IsAssignableFrom(entityType)
                ? foreignKey.DeclaringEntityType
                : foreignKey.PrincipalEntityType);
        }
    /// <summary>
    ///     Returns the default table name that would be used for this entity type.
    /// </summary>
    /// <param name="entityType">The entity type to get the table name for.</param>
    /// <param name="truncate">A value indicating whether the name should be truncated to the max identifier length.</param>
    /// <returns>The default name of the table to which the entity type would be mapped.</returns>
    public static string?GetDefaultTableName(this IReadOnlyEntityType entityType, bool truncate = true)
    {
        var ownership = entityType.FindOwnership();

        if (ownership != null &&
            ownership.IsUnique)
        {
            return(ownership.PrincipalEntityType.GetTableName());
        }

        var name = entityType.ShortName();

        if (entityType.HasSharedClrType &&
            ownership != null
#pragma warning disable EF1001 // Internal EF Core API usage.
            && entityType.Name == ownership.PrincipalEntityType.GetOwnedName(name, ownership.PrincipalToDependent !.Name))
#pragma warning restore EF1001 // Internal EF Core API usage.
        {
            var ownerTypeTable = ownership.PrincipalEntityType.GetTableName();
            name = ownerTypeTable != null
                ? $"{ownerTypeTable}_{ownership.PrincipalToDependent.Name}"
                : $"{ownership.PrincipalToDependent.Name}_{name}";
        }

        return(truncate
            ? Uniquifier.Truncate(name, entityType.Model.GetMaxIdentifierLength())
            : name);
    }
Ejemplo n.º 10
0
        /// <summary>
        ///     Creates an id for the store object that the given entity type is mapped to.
        /// </summary>
        /// <param name="entityType"> The entity type. </param>
        /// <param name="type"> The store object type. </param>
        /// <returns> The store object id. </returns>
        public static StoreObjectIdentifier?Create(IReadOnlyEntityType entityType, StoreObjectType type)
        {
            Check.NotNull(entityType, nameof(entityType));

            switch (type)
            {
            case StoreObjectType.Table:
                var tableName = entityType.GetTableName();
                return(tableName == null ? null : Table(tableName, entityType.GetSchema()));

            case StoreObjectType.View:
                var viewName = entityType.GetViewName();
                return(viewName == null ? null : View(viewName, entityType.GetViewSchema()));

            case StoreObjectType.SqlQuery:
                var query = entityType.GetSqlQuery();
                return(query == null ? null : SqlQuery(entityType));

            case StoreObjectType.Function:
                var functionName = entityType.GetFunctionName();
                return(functionName == null ? null : DbFunction(functionName));

            default:
                return(null);
            }
        }
Ejemplo n.º 11
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 IReadOnlyTrigger?FindDeclaredTrigger(IReadOnlyEntityType entityType, string name)
    {
        var triggers = (SortedDictionary <string, ITrigger>?)entityType[RelationalAnnotationNames.Triggers];

        return(triggers is not null && triggers.TryGetValue(name, out var trigger)
            ? trigger
            : null);
    }
Ejemplo n.º 12
0
 /// <summary>
 ///     Constructs the event payload.
 /// </summary>
 /// <param name="eventDefinition"> The event definition. </param>
 /// <param name="messageGenerator"> A delegate that generates a log message for this event. </param>
 /// <param name="entityType"> The entityType. </param>
 public EntityTypeEventData(
     EventDefinitionBase eventDefinition,
     Func <EventDefinitionBase, EventData, string> messageGenerator,
     IReadOnlyEntityType entityType)
     : base(eventDefinition, messageGenerator)
 {
     EntityType = entityType;
 }
    /// <summary>
    ///     Finds an <see cref="IReadOnlyCheckConstraint" /> with the given name.
    /// </summary>
    /// <param name="entityType">The entity type to find the check constraint for.</param>
    /// <param name="name">The check constraint name.</param>
    /// <returns>
    ///     The <see cref="IReadOnlyCheckConstraint" /> or <see langword="null" /> if no check constraint with the
    ///     given name in the given entity type was found.
    /// </returns>
    public static IReadOnlyCheckConstraint?FindCheckConstraint(
        this IReadOnlyEntityType entityType,
        string name)
    {
        Check.NotEmpty(name, nameof(name));

        return(CheckConstraint.FindCheckConstraint(entityType, name));
    }
Ejemplo n.º 14
0
 /// <summary>
 ///     Creates a <see cref="ParameterBinding" /> for the given type and name on the given entity type.
 /// </summary>
 /// <param name="entityType">The entity type.</param>
 /// <param name="parameterType">The parameter type.</param>
 /// <param name="parameterName">The parameter name.</param>
 /// <returns>The binding.</returns>
 public virtual ParameterBinding Bind(
     IReadOnlyEntityType entityType,
     Type parameterType,
     string parameterName)
 => new DependencyInjectionParameterBinding(
     _serviceType,
     _serviceType,
     entityType.GetServiceProperties().Cast <IPropertyBase>().Where(p => p.ClrType == _serviceType).ToArray());
Ejemplo n.º 15
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 IEnumerable <IReadOnlyCheckConstraint> GetDeclaredCheckConstraints(IReadOnlyEntityType entityType)
    {
        if (entityType is RuntimeEntityType)
        {
            throw new InvalidOperationException(CoreStrings.RuntimeModelMissingData);
        }

        return(GetConstraintsDictionary(entityType)?.Values ?? Enumerable.Empty <ICheckConstraint>());
    }
    /// <summary>
    ///     Gets the foreign keys for the given entity type that point to other entity types
    ///     sharing the same table-like store object.
    /// </summary>
    /// <param name="entityType">The entity type.</param>
    /// <param name="storeObject">The identifier of the store object.</param>
    public static IEnumerable <IReadOnlyForeignKey> FindRowInternalForeignKeys(
        this IReadOnlyEntityType entityType,
        StoreObjectIdentifier storeObject)
    {
        var primaryKey = entityType.FindPrimaryKey();

        if (primaryKey == null)
        {
            yield break;
        }

        foreach (var foreignKey in entityType.GetForeignKeys())
        {
            var principalEntityType = foreignKey.PrincipalEntityType;
            if (!foreignKey.PrincipalKey.IsPrimaryKey() ||
                principalEntityType == foreignKey.DeclaringEntityType ||
                !foreignKey.IsUnique
#pragma warning disable EF1001 // Internal EF Core API usage.
                || !PropertyListComparer.Instance.Equals(foreignKey.Properties, primaryKey.Properties))
#pragma warning restore EF1001 // Internal EF Core API usage.
            {
                continue;
            }

            switch (storeObject.StoreObjectType)
            {
            case StoreObjectType.Table:
                if (storeObject.Name == principalEntityType.GetTableName() &&
                    storeObject.Schema == principalEntityType.GetSchema())
                {
                    yield return(foreignKey);
                }

                break;

            case StoreObjectType.View:
                if (storeObject.Name == principalEntityType.GetViewName() &&
                    storeObject.Schema == principalEntityType.GetViewSchema())
                {
                    yield return(foreignKey);
                }

                break;

            case StoreObjectType.Function:
                if (storeObject.Name == principalEntityType.GetFunctionName())
                {
                    yield return(foreignKey);
                }

                break;

            default:
                throw new NotSupportedException(storeObject.StoreObjectType.ToString());
            }
        }
    }
Ejemplo n.º 17
0
        public static IReadOnlyEntityType?GetClosestCommonParent([NotNull] this IReadOnlyEntityType entityType1, [NotNull] IReadOnlyEntityType entityType2)
        {
            Check.NotNull(entityType1, nameof(entityType1));
            Check.NotNull(entityType2, nameof(entityType2));

            return(entityType1
                   .GetAllBaseTypesInclusiveAscending()
                   .FirstOrDefault(i => entityType2.GetAllBaseTypesInclusiveAscending().Any(j => j == i)));
        }
    /// <summary>
    ///     Returns the default view name that would be used for this entity type.
    /// </summary>
    /// <param name="entityType">The entity type to get the table name for.</param>
    /// <returns>The default name of the table to which the entity type would be mapped.</returns>
    public static string?GetDefaultViewName(this IReadOnlyEntityType entityType)
    {
        var ownership = entityType.FindOwnership();

        return(ownership != null &&
               ownership.IsUnique
                ? ownership.PrincipalEntityType.GetViewName()
                : null);
    }
Ejemplo n.º 19
0
 private static void CloneIndexes(IReadOnlyEntityType sourceEntityType, IMutableEntityType targetEntityType)
 {
     foreach (var index in sourceEntityType.GetDeclaredIndexes())
     {
         var clonedIndex = targetEntityType.AddIndex(
             index.Properties.Select(p => targetEntityType.FindProperty(p.Name)).ToList());
         clonedIndex.IsUnique = index.IsUnique;
         index.GetAnnotations().ForEach(annotation => clonedIndex[annotation.Name] = annotation.Value);
     }
 }
Ejemplo n.º 20
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 IReadOnlyCheckConstraint?FindDeclaredCheckConstraint(IReadOnlyEntityType entityType, string name)
        {
            var dataDictionary = GetConstraintsDictionary(entityType);

            return(dataDictionary == null
                ? null
                : dataDictionary.TryGetValue(name, out var checkConstraint)
                    ? checkConstraint
                    : null);
        }
Ejemplo n.º 21
0
        public static IReadOnlyEntityType?LeastDerivedType([NotNull] this IReadOnlyEntityType entityType, [NotNull] IReadOnlyEntityType otherEntityType)
        {
            Check.NotNull(entityType, nameof(entityType));
            Check.NotNull(otherEntityType, nameof(otherEntityType));

            return(entityType.IsAssignableFrom(otherEntityType)
                ? entityType
                : otherEntityType.IsAssignableFrom(entityType)
                    ? otherEntityType
                    : null);
        }
Ejemplo n.º 22
0
        public static IReadOnlyNavigation?FindDefiningNavigation([NotNull] this IReadOnlyEntityType entityType)
        {
            if (!entityType.HasDefiningNavigation())
            {
                return(null);
            }

            var definingNavigation = entityType.DefiningEntityType !.FindNavigation(entityType.DefiningNavigationName !);

            return(definingNavigation?.TargetEntityType == entityType ? definingNavigation : null);
        }
Ejemplo n.º 23
0
        /// <summary>
        ///     Creates a <see cref="ParameterBinding" /> for the given type and name on the given entity type.
        /// </summary>
        /// <param name="entityType"> The entity type. </param>
        /// <param name="parameterType"> The parameter type. </param>
        /// <param name="parameterName"> The parameter name. </param>
        /// <returns> The binding. </returns>
        public override ParameterBinding Bind(
            IReadOnlyEntityType entityType,
            Type parameterType,
            string parameterName)
        {
            Check.NotNull(entityType, nameof(entityType));
            Check.NotNull(parameterType, nameof(parameterType));
            Check.NotEmpty(parameterName, nameof(parameterName));

            return(Bind((IEntityType)entityType, parameterType));
        }
Ejemplo n.º 24
0
        private void ProcessElement(IReadOnlyEntityType entityType, string version)
        {
            ProcessElement((IReadOnlyAnnotatable)entityType, version);

            if ((version.StartsWith("2.0", StringComparison.Ordinal) ||
                 version.StartsWith("2.1", StringComparison.Ordinal)) &&
                entityType is IMutableEntityType mutableEntityType &&
                !entityType.IsOwned())
            {
                UpdateOwnedTypes(mutableEntityType);
            }
        }
    /// <summary>
    ///     Returns the default database schema that would be used for this entity view.
    /// </summary>
    /// <param name="entityType">The entity type to get the view schema for.</param>
    /// <returns>The default database schema to which the entity type would be mapped.</returns>
    public static string?GetDefaultViewSchema(this IReadOnlyEntityType entityType)
    {
        var ownership = entityType.FindOwnership();

        if (ownership != null &&
            ownership.IsUnique)
        {
            return(ownership.PrincipalEntityType.GetViewSchema());
        }

        return(GetViewName(entityType) != null?entityType.Model.GetDefaultSchema() : null);
    }
        public static string?GetSchemaQualifiedTableName([NotNull] this IReadOnlyEntityType entityType)
        {
            var tableName = entityType.GetTableName();

            if (tableName == null)
            {
                return(null);
            }

            var schema = entityType.GetSchema();

            return((string.IsNullOrEmpty(schema) ? "" : schema + ".") + tableName);
        }
    /// <summary>
    ///     Returns the database schema that contains the mapped view.
    /// </summary>
    /// <param name="entityType">The entity type to get the view schema for.</param>
    /// <returns>The database schema that contains the mapped view.</returns>
    public static string?GetViewSchema(this IReadOnlyEntityType entityType)
    {
        var schemaAnnotation = entityType.FindAnnotation(RelationalAnnotationNames.ViewSchema);

        if (schemaAnnotation != null)
        {
            return((string?)schemaAnnotation.Value ?? GetDefaultViewSchema(entityType));
        }

        return(entityType.BaseType != null
            ? entityType.GetRootType().GetViewSchema()
            : GetDefaultViewSchema(entityType));
    }
    /// <summary>
    ///     Returns the name of the view to which the entity type is mapped prepended by the schema
    ///     or <see langword="null" /> if not mapped to a view.
    /// </summary>
    /// <param name="entityType">The entity type to get the table name for.</param>
    /// <returns>The name of the table to which the entity type is mapped prepended by the schema.</returns>
    public static string?GetSchemaQualifiedViewName(this IReadOnlyEntityType entityType)
    {
        var viewName = entityType.GetViewName();

        if (viewName == null)
        {
            return(null);
        }

        var schema = entityType.GetViewSchema();

        return((string.IsNullOrEmpty(schema) ? "" : schema + ".") + viewName);
    }
Ejemplo n.º 29
0
 private static void CloneProperties(IReadOnlyEntityType sourceEntityType, IMutableEntityType targetEntityType)
 {
     foreach (var property in sourceEntityType.GetDeclaredProperties())
     {
         var clonedProperty = targetEntityType.AddProperty(property.Name, property.ClrType);
         clonedProperty.IsNullable         = property.IsNullable;
         clonedProperty.IsConcurrencyToken = property.IsConcurrencyToken;
         clonedProperty.ValueGenerated     = property.ValueGenerated;
         clonedProperty.SetBeforeSaveBehavior(property.GetBeforeSaveBehavior());
         clonedProperty.SetAfterSaveBehavior(property.GetAfterSaveBehavior());
         property.GetAnnotations().ForEach(annotation => clonedProperty[annotation.Name] = annotation.Value);
     }
 }
Ejemplo n.º 30
0
        public static MemberInfo GetNavigationMemberInfo(
            [NotNull] this IReadOnlyEntityType entityType,
            [NotNull] string navigationName)
        {
            var memberInfo = entityType.ClrType.GetMembersInHierarchy(navigationName).FirstOrDefault();

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

            return(memberInfo);
        }