Exemplo n.º 1
0
        private object InstantiateEntity(
            EntityType entityType,
            DbContext context,
            Type clrType,
            DbSet set)
        {
            object structuralObject;

            if (!clrType.IsAbstract())
            {
                structuralObject = set.Create();
            }
            else
            {
                EntityType entityType1 = this._metadataWorkspace.GetItems <EntityType>(DataSpace.CSpace).First <EntityType>((Func <EntityType, bool>)(et =>
                {
                    if (entityType.IsAncestorOf(et))
                    {
                        return(!et.Abstract);
                    }
                    return(false);
                }));
                structuralObject = context.Set(EntityTypeExtensions.GetClrType(entityType1)).Create();
            }
            ModificationCommandTreeGenerator.InstantiateComplexProperties(structuralObject, (IEnumerable <EdmProperty>)entityType.Properties);
            return(structuralObject);
        }
Exemplo n.º 2
0
        private void GenerateIndependentAssociationType(
            AssociationType associationType,
            DbDatabaseMapping databaseMapping)
        {
            AssociationEndMember principalEnd;
            AssociationEndMember dependentEnd;

            if (!associationType.TryGuessPrincipalAndDependentEnds(out principalEnd, out dependentEnd))
            {
                if (!associationType.IsPrincipalConfigured())
                {
                    throw Error.UnableToDeterminePrincipal((object)EntityTypeExtensions.GetClrType(associationType.SourceEnd.GetEntityType()), (object)EntityTypeExtensions.GetClrType(associationType.TargetEnd.GetEntityType()));
                }
                principalEnd = associationType.SourceEnd;
                dependentEnd = associationType.TargetEnd;
            }
            EntityTypeMapping     mappingInHierarchy = StructuralTypeMappingGenerator.GetEntityTypeMappingInHierarchy(databaseMapping, dependentEnd.GetEntityType());
            EntityType            table = mappingInHierarchy.MappingFragments.First <MappingFragment>().Table;
            AssociationSetMapping associationSetMapping = AssociationTypeMappingGenerator.GenerateAssociationSetMapping(associationType, databaseMapping, principalEnd, dependentEnd, table);

            this.GenerateIndependentForeignKeyConstraint(databaseMapping, principalEnd.GetEntityType(), dependentEnd.GetEntityType(), table, associationSetMapping, associationSetMapping.SourceEndMapping, associationType.Name, principalEnd, false);
            foreach (EdmProperty keyProperty in dependentEnd.GetEntityType().KeyProperties())
            {
                associationSetMapping.TargetEndMapping.AddPropertyMapping(new ScalarPropertyMapping(keyProperty, mappingInHierarchy.GetPropertyMapping(keyProperty).ColumnProperty));
            }
        }
Exemplo n.º 3
0
 private void ConfigureFunctionMappings(
     EdmModel model,
     EntityTypeConfiguration entityTypeConfiguration,
     EntityType entityType)
 {
     if (entityTypeConfiguration.ModificationStoredProceduresConfiguration == null)
     {
         return;
     }
     for (; entityType.BaseType != null; entityType = (EntityType)entityType.BaseType)
     {
         Type clrType = EntityTypeExtensions.GetClrType((EntityType)entityType.BaseType);
         EntityTypeConfiguration typeConfiguration;
         if (!entityType.BaseType.Abstract && (!this._entityConfigurations.TryGetValue(clrType, out typeConfiguration) || typeConfiguration.ModificationStoredProceduresConfiguration == null))
         {
             throw Error.BaseTypeNotMappedToFunctions((object)clrType.Name, (object)entityTypeConfiguration.ClrType.Name);
         }
     }
     model.GetSelfAndAllDerivedTypes(entityType).Each <EntityType>((Action <EntityType>)(e =>
     {
         EntityTypeConfiguration typeConfiguration = this.Entity(EntityTypeExtensions.GetClrType(e));
         if (typeConfiguration.ModificationStoredProceduresConfiguration != null)
         {
             return;
         }
         typeConfiguration.MapToStoredProcedures();
     }));
 }
Exemplo n.º 4
0
        private object InstantiateAndAttachEntity(EntityType entityType, DbContext context)
        {
            Type   clrType = EntityTypeExtensions.GetClrType(entityType);
            DbSet  set     = context.Set(clrType);
            object entity  = this.InstantiateEntity(entityType, context, clrType, set);

            ModificationCommandTreeGenerator.SetFakeReferenceKeyValues(entity, entityType);
            ModificationCommandTreeGenerator.SetFakeKeyValues(entity, entityType);
            set.Attach(entity);
            return(entity);
        }
Exemplo n.º 5
0
        private void ChangeRelationshipStates(
            DbContext context,
            EntityType entityType,
            object entity,
            EntityState state)
        {
            ObjectStateManager objectStateManager = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager;

            foreach (AssociationType associationType in this._metadataWorkspace.GetItems <AssociationType>(DataSpace.CSpace).Where <AssociationType>((Func <AssociationType, bool>)(at =>
            {
                if (at.IsForeignKey || at.IsManyToMany())
                {
                    return(false);
                }
                if (!at.SourceEnd.GetEntityType().IsAssignableFrom((EdmType)entityType))
                {
                    return(at.TargetEnd.GetEntityType().IsAssignableFrom((EdmType)entityType));
                }
                return(true);
            })))
            {
                AssociationEndMember principalEnd;
                AssociationEndMember dependentEnd;
                if (!associationType.TryGuessPrincipalAndDependentEnds(out principalEnd, out dependentEnd))
                {
                    principalEnd = associationType.SourceEnd;
                    dependentEnd = associationType.TargetEnd;
                }
                if (dependentEnd.GetEntityType().IsAssignableFrom((EdmType)entityType))
                {
                    EntityType entityType1 = principalEnd.GetEntityType();
                    Type       clrType     = EntityTypeExtensions.GetClrType(entityType1);
                    DbSet      set         = context.Set(clrType);
                    object     obj1        = set.Local.Cast <object>().SingleOrDefault <object>();
                    if (obj1 == null || object.ReferenceEquals(entity, obj1) && state == EntityState.Added)
                    {
                        obj1 = this.InstantiateEntity(entityType1, context, clrType, set);
                        ModificationCommandTreeGenerator.SetFakeReferenceKeyValues(obj1, entityType1);
                        set.Attach(obj1);
                    }
                    if (principalEnd.IsRequired() && state == EntityState.Modified)
                    {
                        object obj2 = this.InstantiateEntity(entityType1, context, clrType, set);
                        ModificationCommandTreeGenerator.SetFakeKeyValues(obj2, entityType1);
                        set.Attach(obj2);
                        objectStateManager.ChangeRelationshipState(entity, obj2, associationType.FullName, principalEnd.Name, EntityState.Deleted);
                    }
                    objectStateManager.ChangeRelationshipState(entity, obj1, associationType.FullName, principalEnd.Name, state == EntityState.Deleted ? state : EntityState.Added);
                }
            }
        }
Exemplo n.º 6
0
        public void Generate(EntityType entityType, DbDatabaseMapping databaseMapping)
        {
            EntitySet         entitySet          = databaseMapping.Model.GetEntitySet(entityType);
            EntitySetMapping  entitySetMapping   = databaseMapping.GetEntitySetMapping(entitySet) ?? databaseMapping.AddEntitySetMapping(entitySet);
            EntityTypeMapping entityTypeMapping1 = entitySetMapping.EntityTypeMappings.FirstOrDefault <EntityTypeMapping>((Func <EntityTypeMapping, bool>)(m => m.EntityTypes.Contains((EntityTypeBase)entitySet.ElementType))) ?? entitySetMapping.EntityTypeMappings.FirstOrDefault <EntityTypeMapping>();
            EntityType        entityType1        = entityTypeMapping1 != null?entityTypeMapping1.MappingFragments.First <MappingFragment>().Table : databaseMapping.Database.AddTable(entityType.GetRootType().Name);

            EntityTypeMapping entityTypeMapping2 = new EntityTypeMapping((EntitySetMapping)null);
            MappingFragment   mappingFragment    = new MappingFragment(databaseMapping.Database.GetEntitySet(entityType1), (TypeMapping)entityTypeMapping2, false);

            entityTypeMapping2.AddType(entityType);
            entityTypeMapping2.AddFragment(mappingFragment);
            entityTypeMapping2.SetClrType(EntityTypeExtensions.GetClrType(entityType));
            entitySetMapping.AddTypeMapping(entityTypeMapping2);
            new PropertyMappingGenerator(this._providerManifest).Generate(entityType, (IEnumerable <EdmProperty>)entityType.Properties, entitySetMapping, mappingFragment, (IList <EdmProperty>) new List <EdmProperty>(), false);
        }
Exemplo n.º 7
0
        private void ConfigureKey(EntityType entityType)
        {
            if (!this._keyProperties.Any <PropertyInfo>())
            {
                return;
            }
            if (entityType.BaseType != null)
            {
                throw Error.KeyRegisteredOnDerivedType((object)this.ClrType, (object)EntityTypeExtensions.GetClrType(entityType.GetRootType()));
            }
            IEnumerable <PropertyInfo> propertyInfos = this._keyProperties.AsEnumerable <PropertyInfo>();

            if (!this._isKeyConfigured)
            {
                IEnumerable <\u003C\u003Ef__AnonymousType41 <PropertyInfo, int?> > source = this._keyProperties.Select(p => new
                {
                    PropertyInfo = p,
                    ColumnOrder  = this.Property(new PropertyPath(p), new OverridableConfigurationParts?()).ColumnOrder
                });
                if (this._keyProperties.Count > 1 && source.Any(p => !p.ColumnOrder.HasValue))
                {
                    throw Error.ModelGeneration_UnableToDetermineKeyOrder((object)this.ClrType);
                }
                propertyInfos = source.OrderBy(p => p.ColumnOrder).Select(p => p.PropertyInfo);
            }
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                EdmProperty primitiveProperty = entityType.GetDeclaredPrimitiveProperty(propertyInfo);
                if (primitiveProperty == null)
                {
                    throw Error.KeyPropertyNotFound((object)propertyInfo.Name, (object)entityType.Name);
                }
                primitiveProperty.Nullable = false;
                entityType.AddKeyMember((EdmMember)primitiveProperty);
            }
        }
Exemplo n.º 8
0
        internal override void Configure(
            AssociationType associationType,
            AssociationEndMember dependentEnd,
            EntityTypeConfiguration entityTypeConfiguration)
        {
            // ISSUE: object of a compiler-generated type is created
            // ISSUE: variable of a compiler-generated type
            ForeignKeyConstraintConfiguration.\u003C\u003Ec__DisplayClasse cDisplayClasse1 = new ForeignKeyConstraintConfiguration.\u003C\u003Ec__DisplayClasse();
            // ISSUE: reference to a compiler-generated field
            cDisplayClasse1.entityTypeConfiguration = entityTypeConfiguration;
            if (!this._dependentProperties.Any <PropertyInfo>())
            {
                return;
            }
            IEnumerable <PropertyInfo> propertyInfos = this._dependentProperties.AsEnumerable <PropertyInfo>();

            if (!this.IsFullySpecified)
            {
                // ISSUE: reference to a compiler-generated field
                if (EntityTypeExtensions.GetClrType(dependentEnd.GetEntityType()) != cDisplayClasse1.entityTypeConfiguration.ClrType)
                {
                    return;
                }
                // ISSUE: reference to a compiler-generated method
                IEnumerable <\u003C\u003Ef__AnonymousType41 <PropertyInfo, int?> > source = this._dependentProperties.Select(new Func <PropertyInfo, \u003C\u003Ef__AnonymousType41 <PropertyInfo, int?> >(cDisplayClasse1.\u003CConfigure\u003Eb__0));
                if (this._dependentProperties.Count > 1 && source.Any(p => !p.ColumnOrder.HasValue))
                {
                    ReadOnlyMetadataCollection <EdmProperty> dependentKeys = dependentEnd.GetEntityType().KeyProperties;
                    if (dependentKeys.Count != this._dependentProperties.Count || !source.All(fk =>
                    {
                        // ISSUE: variable of a compiler-generated type
                        ForeignKeyConstraintConfiguration.\u003C\u003Ec__DisplayClasse cDisplayClasse = cDisplayClasse1;
                        var fk1 = fk;
                        return(dependentKeys.Any <EdmProperty>((Func <EdmProperty, bool>)(p => p.GetClrPropertyInfo().IsSameAs(fk1.PropertyInfo))));
                    }))
                    {
                        // ISSUE: reference to a compiler-generated field
                        throw Error.ForeignKeyAttributeConvention_OrderRequired((object)cDisplayClasse1.entityTypeConfiguration.ClrType);
                    }
                    propertyInfos = dependentKeys.Select <EdmProperty, PropertyInfo>((Func <EdmProperty, PropertyInfo>)(p => p.GetClrPropertyInfo()));
                }
                else
                {
                    propertyInfos = source.OrderBy(p => p.ColumnOrder).Select(p => p.PropertyInfo);
                }
            }
            List <EdmProperty> edmPropertyList = new List <EdmProperty>();

            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                EdmProperty primitiveProperty = dependentEnd.GetEntityType().GetDeclaredPrimitiveProperty(propertyInfo);
                if (primitiveProperty == null)
                {
                    throw Error.ForeignKeyPropertyNotFound((object)propertyInfo.Name, (object)dependentEnd.GetEntityType().Name);
                }
                edmPropertyList.Add(primitiveProperty);
            }
            AssociationEndMember  otherEnd = associationType.GetOtherEnd(dependentEnd);
            ReferentialConstraint referentialConstraint = new ReferentialConstraint((RelationshipEndMember)otherEnd, (RelationshipEndMember)dependentEnd, (IEnumerable <EdmProperty>)otherEnd.GetEntityType().KeyProperties, (IEnumerable <EdmProperty>)edmPropertyList);

            if (otherEnd.IsRequired())
            {
                referentialConstraint.ToProperties.Each <EdmProperty, bool>((Func <EdmProperty, bool>)(p => p.Nullable = false));
            }
            associationType.Constraint = referentialConstraint;
        }
Exemplo n.º 9
0
 /// <inheritdoc />
 public virtual void Apply(EntityType item, DbModel model)
 {
     Check.NotNull <EntityType>(item, nameof(item));
     Check.NotNull <DbModel>(model, nameof(model));
     if (item.BaseType != null)
     {
         return;
     }
     foreach (EdmProperty keyProperty in item.KeyProperties)
     {
         item.RemoveMember((EdmMember)keyProperty);
         item.AddKeyMember((EdmMember)keyProperty);
     }
     foreach (PropertyInfo property in new PropertyFilter(DbModelBuilderVersion.Latest).GetProperties(EntityTypeExtensions.GetClrType(item), false, (IEnumerable <PropertyInfo>)null, (IEnumerable <Type>)null, true))
     {
         PropertyInfo p           = property;
         EdmProperty  edmProperty = item.DeclaredProperties.SingleOrDefault <EdmProperty>((Func <EdmProperty, bool>)(ep => ep.Name == p.Name));
         if (edmProperty != null && !item.KeyProperties.Contains(edmProperty))
         {
             item.RemoveMember((EdmMember)edmProperty);
             item.AddMember((EdmMember)edmProperty);
         }
     }
 }
Exemplo n.º 10
0
        public HistoryRepository(
            InternalContext usersContext,
            string connectionString,
            DbProviderFactory providerFactory,
            string contextKey,
            int?commandTimeout,
            Func <DbConnection, string, HistoryContext> historyContextFactory,
            IEnumerable <string> schemas            = null,
            DbContext contextForInterception        = null,
            DatabaseExistenceState initialExistence = DatabaseExistenceState.Unknown)
            : base(usersContext, connectionString, providerFactory)
        {
            this._initialExistence    = initialExistence;
            this._commandTimeout      = commandTimeout;
            this._existingTransaction = usersContext.TryGetCurrentStoreTransaction();
            this._schemas             = ((IEnumerable <string>) new string[1]
            {
                "dbo"
            }).Concat <string>(schemas ?? Enumerable.Empty <string>()).Distinct <string>();
            this._contextForInterception = contextForInterception;
            this._historyContextFactory  = historyContextFactory;
            DbConnection connection = (DbConnection)null;

            try
            {
                connection = this.CreateConnection();
                using (HistoryContext context = this.CreateContext(connection, (string)null))
                {
                    EntityType entityType = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace.GetItems <EntityType>(DataSpace.CSpace).Single <EntityType>((Func <EntityType, bool>)(et => EntityTypeExtensions.GetClrType(et) == typeof(HistoryRow)));
                    int?       maxLength  = entityType.Properties.Single <EdmProperty>((Func <EdmProperty, bool>)(p => p.GetClrPropertyInfo().IsSameAs(HistoryRepository.MigrationIdProperty))).MaxLength;
                    this._migrationIdMaxLength = maxLength.HasValue ? maxLength.Value : 150;
                    maxLength = entityType.Properties.Single <EdmProperty>((Func <EdmProperty, bool>)(p => p.GetClrPropertyInfo().IsSameAs(HistoryRepository.ContextKeyProperty))).MaxLength;
                    this._contextKeyMaxLength = maxLength.HasValue ? maxLength.Value : 300;
                }
            }
            finally
            {
                this.DisposeConnection(connection);
            }
            this._contextKey = contextKey.RestrictTo(this._contextKeyMaxLength);
        }
Exemplo n.º 11
0
        internal void Configure(
            EntityType entityType,
            DbDatabaseMapping databaseMapping,
            DbProviderManifest providerManifest)
        {
            EntityTypeMapping entityTypeMapping = databaseMapping.GetEntityTypeMapping(EntityTypeExtensions.GetClrType(entityType));

            if (entityTypeMapping != null)
            {
                EntityTypeConfiguration.VerifyAllCSpacePropertiesAreMapped((ICollection <EntityTypeMapping>)databaseMapping.GetEntityTypeMappings(entityType).ToList <EntityTypeMapping>(), (IEnumerable <EdmProperty>)entityTypeMapping.EntityType.DeclaredProperties, (IList <EdmProperty>) new List <EdmProperty>());
            }
            this.ConfigurePropertyMappings(databaseMapping, entityType, providerManifest, false);
            this.ConfigureAssociationMappings(databaseMapping, entityType, providerManifest);
            EntityTypeConfiguration.ConfigureDependentKeys(databaseMapping, providerManifest);
            this.ConfigureModificationStoredProcedures(databaseMapping, entityType, providerManifest);
        }
Exemplo n.º 12
0
        internal static void ConfigureUnconfiguredType(
            DbDatabaseMapping databaseMapping,
            ICollection <EntitySet> entitySets,
            DbProviderManifest providerManifest,
            EntityType entityType,
            IDictionary <string, object> commonAnnotations)
        {
            EntityMappingConfiguration mappingConfiguration = new EntityMappingConfiguration();
            EntityTypeMapping          entityTypeMapping    = databaseMapping.GetEntityTypeMapping(EntityTypeExtensions.GetClrType(entityType));

            mappingConfiguration.Configure(databaseMapping, entitySets, providerManifest, entityType, ref entityTypeMapping, false, 0, 1, commonAnnotations);
        }
Exemplo n.º 13
0
 private static IEnumerable <EdmProperty> GetDependentProperties(
     EntityType dependentType,
     IEnumerable <string> dependentPropertyNames,
     EntityType declaringEntityType,
     NavigationProperty navigationProperty)
 {
     foreach (string dependentPropertyName1 in dependentPropertyNames)
     {
         string dependentPropertyName = dependentPropertyName1;
         if (string.IsNullOrWhiteSpace(dependentPropertyName))
         {
             throw Error.ForeignKeyAttributeConvention_EmptyKey((object)navigationProperty.Name, (object)EntityTypeExtensions.GetClrType(declaringEntityType));
         }
         EdmProperty dependentProperty = dependentType.Properties.SingleOrDefault <EdmProperty>((Func <EdmProperty, bool>)(p => p.Name.Equals(dependentPropertyName, StringComparison.Ordinal)));
         if (dependentProperty == null)
         {
             throw Error.ForeignKeyAttributeConvention_InvalidKey((object)navigationProperty.Name, (object)EntityTypeExtensions.GetClrType(declaringEntityType), (object)dependentPropertyName, (object)EntityTypeExtensions.GetClrType(dependentType));
         }
         yield return(dependentProperty);
     }
 }
Exemplo n.º 14
0
 private static void GenerateEntityTypes(DbDatabaseMapping databaseMapping)
 {
     foreach (EntityType entityType1 in databaseMapping.Model.EntityTypes)
     {
         EntityType entityType = entityType1;
         if (entityType.Abstract && databaseMapping.Model.EntityTypes.All <EntityType>((Func <EntityType, bool>)(e => e.BaseType != entityType)))
         {
             throw new InvalidOperationException(Strings.UnmappedAbstractType((object)EntityTypeExtensions.GetClrType(entityType)));
         }
         new TableMappingGenerator(databaseMapping.ProviderManifest).Generate(entityType, databaseMapping);
     }
 }
Exemplo n.º 15
0
        private IList <EntityTypeConfiguration> SortEntityConfigurationsByInheritance(
            DbDatabaseMapping databaseMapping)
        {
            List <EntityTypeConfiguration> typeConfigurationList = new List <EntityTypeConfiguration>();

            foreach (EntityTypeConfiguration entityConfiguration in this.ActiveEntityConfigurations)
            {
                EntityType entityType = databaseMapping.Model.GetEntityType(entityConfiguration.ClrType);
                if (entityType != null)
                {
                    if (entityType.BaseType == null)
                    {
                        if (!typeConfigurationList.Contains(entityConfiguration))
                        {
                            typeConfigurationList.Add(entityConfiguration);
                        }
                    }
                    else
                    {
                        Stack <EntityType> entityTypeStack = new Stack <EntityType>();
                        for (; entityType != null; entityType = (EntityType)entityType.BaseType)
                        {
                            entityTypeStack.Push(entityType);
                        }
                        while (entityTypeStack.Count > 0)
                        {
                            entityType = entityTypeStack.Pop();
                            EntityTypeConfiguration typeConfiguration = this.ActiveEntityConfigurations.SingleOrDefault <EntityTypeConfiguration>((Func <EntityTypeConfiguration, bool>)(ec => ec.ClrType == EntityTypeExtensions.GetClrType(entityType)));
                            if (typeConfiguration != null && !typeConfigurationList.Contains(typeConfiguration))
                            {
                                typeConfigurationList.Add(typeConfiguration);
                            }
                        }
                    }
                }
            }
            return((IList <EntityTypeConfiguration>)typeConfigurationList);
        }
Exemplo n.º 16
0
        private static void ConfigureUnconfiguredDerivedTypes(
            DbDatabaseMapping databaseMapping,
            ICollection <EntitySet> entitySets,
            DbProviderManifest providerManifest,
            EntityType entityType,
            IList <EntityTypeConfiguration> sortedEntityConfigurations)
        {
            List <EntityType> list = databaseMapping.Model.GetDerivedTypes(entityType).ToList <EntityType>();

            while (list.Count > 0)
            {
                EntityType currentType = list[0];
                list.RemoveAt(0);
                if (!currentType.Abstract && sortedEntityConfigurations.All <EntityTypeConfiguration>((Func <EntityTypeConfiguration, bool>)(etc => etc.ClrType != EntityTypeExtensions.GetClrType(currentType))))
                {
                    EntityTypeConfiguration.ConfigureUnconfiguredType(databaseMapping, entitySets, providerManifest, currentType, (IDictionary <string, object>) new Dictionary <string, object>());
                    list.AddRange(databaseMapping.Model.GetDerivedTypes(currentType));
                }
            }
        }