コード例 #1
0
 /// <summary>
 /// Builds the name for the <see cref="AssociationInfo"/>.
 /// </summary>
 /// <param name="ownerType">Type of the owner.</param>
 /// <param name="ownerField">The owner field.</param>
 /// <param name="targetType">Type of the target.</param>
 /// <returns>Association name.</returns>
 public string BuildAssociationName(TypeInfo ownerType, FieldInfo ownerField, TypeInfo targetType)
 {
     return(ApplyNamingRules(string.Format(AssociationPattern,
                                           ownerType.Name,
                                           ownerField.Name,
                                           targetType.Name)));
 }
コード例 #2
0
 public override void TestFixtureSetUp()
 {
     base.TestFixtureSetUp();
     CustomerType         = Domain.Model.Types[typeof(Customer)];
     OrderType            = Domain.Model.Types[typeof(Order)];
     ProductType          = Domain.Model.Types[typeof(Product)];
     BookType             = Domain.Model.Types[typeof(Book)];
     TitleType            = Domain.Model.Types[typeof(Title)];
     ITitleType           = Domain.Model.Types[typeof(ITitle)];
     OfferContainerType   = Domain.Model.Types[typeof(OfferContainer)];
     PersonIdField        = Domain.Model.Types[typeof(Person)].Fields["Id"];
     OrderIdField         = Domain.Model.Types[typeof(Order)].Fields["Id"];
     CityField            = CustomerType.Fields["City"];
     AgeField             = Domain.Model.Types[typeof(AdvancedPerson)].Fields["Age"];
     CustomerField        = OrderType.Fields["Customer"];
     EmployeeField        = OrderType.Fields["Employee"];
     DetailsField         = OrderType.Fields["Details"];
     BooksField           = Domain.Model.Types[typeof(Author)].Fields["Books"];
     BookTitleField       = BookType.Fields["Title"];
     TitleBookField       = TitleType.Fields["Book"];
     LanguageField        = TitleType.Fields["Language"];
     TextField            = TitleType.Fields["Text"];
     GraphContainersField = typeof(PrefetchManager).GetField("graphContainers",
                                                             BindingFlags.NonPublic | BindingFlags.Instance);
     PrefetchProcessorField = typeof(SqlSessionHandler).GetField("prefetchManager",
                                                                 BindingFlags.NonPublic | BindingFlags.Instance);
     PrefetchTestHelper.FillDataBase(Domain);
 }
コード例 #3
0
 /// <summary>
 /// Builds foreign key name by association.
 /// </summary>
 /// <returns>Foreign key name.</returns>
 public string BuildReferenceForeignKeyName(TypeInfo ownerType, FieldInfo ownerField, TypeInfo targetType)
 {
     ArgumentValidator.EnsureArgumentNotNull(ownerType, "ownerType");
     ArgumentValidator.EnsureArgumentNotNull(ownerField, "ownerField");
     ArgumentValidator.EnsureArgumentNotNull(targetType, "targetType");
     return(ApplyNamingRules(string.Format(ReferenceForeignKeyFormat, ownerType.Name, ownerField.Name, targetType.Name)));
 }
コード例 #4
0
        public void BuildTypeDiscriminatorMap(TypeDef typeDef, TypeInfo typeInfo)
        {
            if (typeDef.TypeDiscriminatorValue != null)
            {
                var targetField = typeInfo.Fields.SingleOrDefault(f => f.IsTypeDiscriminator && f.Parent == null);
                if (targetField == null)
                {
                    throw new DomainBuilderException(string.Format(Strings.ExTypeDiscriminatorIsNotFoundForXType, typeInfo.Name));
                }

                if (targetField.IsEntity)
                {
                    targetField = targetField.Fields.First();
                    targetField.IsTypeDiscriminator = true;
                }

                typeInfo.TypeDiscriminatorValue =
                    ValueTypeBuilder.AdjustValue(targetField, targetField.ValueType, typeDef.TypeDiscriminatorValue);
                typeInfo.Hierarchy.TypeDiscriminatorMap.RegisterTypeMapping(typeInfo, typeInfo.TypeDiscriminatorValue);
            }

            if (typeDef.IsDefaultTypeInHierarchy)
            {
                typeInfo.Hierarchy.TypeDiscriminatorMap.RegisterDefaultType(typeInfo);
            }
        }
コード例 #5
0
 /// <summary>
 ///   Initializes a new instance of this class.
 /// </summary>
 /// <param name="session">The session.</param>
 protected Structure(Session session)
     : base(session)
 {
     typeInfo = GetTypeInfo();
     tuple    = typeInfo.TuplePrototype.Clone();
     SystemBeforeInitialize(false);
 }
コード例 #6
0
        private HierarchyInfo BuildHierarchyInfo(TypeInfo root, HierarchyDef hierarchyDef)
        {
            var key    = BuildKeyInfo(root, hierarchyDef);
            var schema = hierarchyDef.Schema;

            // Optimization. It there is the only class in hierarchy then ConcreteTable schema is applied
            if (schema != InheritanceSchema.ConcreteTable)
            {
                var node = context.DependencyGraph.TryGetNode(hierarchyDef.Root);
                // No dependencies => no descendants
                if (node == null || node.IncomingEdges.Count(e => e.Kind == EdgeKind.Inheritance) == 0)
                {
                    schema = InheritanceSchema.ConcreteTable;
                }
            }

            var typeDiscriminatorField = hierarchyDef.Root.Fields.FirstOrDefault(f => f.IsTypeDiscriminator);
            var typeDiscriminatorMap   = typeDiscriminatorField != null ? new TypeDiscriminatorMap() : null;

            var hierarchy = new HierarchyInfo(root, key, schema, typeDiscriminatorMap)
            {
                Name = root.Name,
            };

            key.Hierarchy = hierarchy; // Setting backreference
            context.Model.Hierarchies.Add(hierarchy);
            return(hierarchy);
        }
コード例 #7
0
    private void BuildFieldMap(TypeInfo @interface, TypeInfo implementor)
    {
      foreach (var field in @interface.Fields.Where(f => f.IsDeclared)) {
        string explicitName = context.NameBuilder.BuildExplicitFieldName(field.DeclaringType, field.Name);
        FieldInfo implField;
        if (implementor.Fields.TryGetValue(explicitName, out implField))
          implField.IsExplicit = true;
        else {
          if (!implementor.Fields.TryGetValue(field.Name, out implField))
            throw new DomainBuilderException(
              String.Format(Strings.TypeXDoesNotImplementYZField, implementor.Name, @interface.Name, field.Name));
        }

        implField.IsInterfaceImplementation = true;

        if (!implementor.FieldMap.ContainsKey(field))
          implementor.FieldMap.Add(field, implField);
        else
          implementor.FieldMap.Override(field, implField);

        var declaringType = implField.DeclaringType;
        var declaringField = implField.DeclaringField;
        if (implField.IsInherited && declaringType.IsEntity) {
          declaringField.IsInterfaceImplementation = true;
          if (!declaringType.FieldMap.ContainsKey(field))
            declaringType.FieldMap.Add(field, declaringField);
        }
      }
    }
        private int GetForeignKeysCount(TypeInfo typeInfo)
        {
            var tableName = Domain.Handlers.NameBuilder.ApplyNamingRules(typeInfo.MappingName);
            var result    = schema.Tables[tableName].TableConstraints.OfType <ForeignKey>().Count();

            return(result);
        }
コード例 #9
0
 /// <summary>
 /// Called to update the fields describing <see cref="Entity"/>'s version.
 /// </summary>
 /// <param name="changedEntity">The changed entity.</param>
 /// <param name="changedField">The changed field.</param>
 /// <returns>
 /// <see langword="True"/>, if <see cref="VersionInfo"/> was changed;
 /// otherwise, <see langword="false"/>.
 /// </returns>
 protected virtual bool UpdateVersion(Entity changedEntity, FieldInfo changedField)
 {
     foreach (var field in TypeInfo.GetVersionFields().Where(f => f.AutoVersion))
     {
         SetFieldValue(field, VersionGenerator.GenerateNextVersion(GetFieldValue(field)));
     }
     return(true);
 }
コード例 #10
0
        private PartialIndexFilterBuilder(IndexInfo index, ParameterExpression parameter)
        {
            this.index     = index;
            this.parameter = parameter;

            declaringType = index.DeclaringType;
            reflectedType = index.ReflectedType;
        }
コード例 #11
0
 private bool IsAuxiliaryType(TypeInfo type)
 {
   if (!type.IsEntity)
     return false;
   var underlyingBaseType = type.UnderlyingType.BaseType;
   return underlyingBaseType!=null
     && underlyingBaseType.IsGenericType
       && underlyingBaseType.GetGenericTypeDefinition()==typeof (EntitySetItem<,>);
 }
コード例 #12
0
        private IMappedExpression BuildField(Type type, ref int index, ref IEnumerable <Type> types)
        {
//      if (type.IsOfGenericType(typeof (Ref<>))) {
//        var entityType = type.GetGenericType(typeof (Ref<>)).GetGenericArguments()[0];
//        TypeInfo typeInfo = model.Types[entityType];
//        KeyInfo keyProviderInfo = typeInfo.KeyInfo;
//        TupleDescriptor keyTupleDescriptor = keyProviderInfo.TupleDescriptor;
//        KeyExpression entityExpression = KeyExpression.Create(typeInfo, index);
//        index += keyTupleDescriptor.Count;
//        types = types.Concat(keyTupleDescriptor);
//        return Expression.Convert(entityExpression, type);
//      }

            if (type.IsSubclassOf(typeof(Entity)))
            {
                TypeInfo          typeInfo           = model.Types[type];
                KeyInfo           keyInfo            = typeInfo.Key;
                TupleDescriptor   keyTupleDescriptor = keyInfo.TupleDescriptor;
                IMappedExpression expression;
                if (isKeyConverter)
                {
                    expression = KeyExpression.Create(typeInfo, index);
                }
                else
                {
                    var entityExpression = EntityExpression.Create(typeInfo, index, true);
                    entityExpression.IsNullable = true;
                    expression = entityExpression;
                }
                index += keyTupleDescriptor.Count;
                types  = types.Concat(keyTupleDescriptor);
                return(expression);
            }

            if (type.IsSubclassOf(typeof(Structure)))
            {
                TypeInfo            typeInfo            = model.Types[type];
                TupleDescriptor     tupleDescriptor     = typeInfo.TupleDescriptor;
                var                 tupleSegment        = new Segment <int>(index, tupleDescriptor.Count);
                StructureExpression structureExpression = StructureExpression.CreateLocalCollectionStructure(typeInfo, tupleSegment);
                index += tupleDescriptor.Count;
                types  = types.Concat(tupleDescriptor);
                return(structureExpression);
            }

            if (TypeIsStorageMappable(type))
            {
                ColumnExpression columnExpression = ColumnExpression.Create(type, index);
                types = types.AddOne(type);
                index++;
                return(columnExpression);
            }

            throw new NotSupportedException();
        }
コード例 #13
0
        public static KeyExpression Create(TypeInfo entityType, int offset)
        {
            var mapping = new Segment <int>(offset, entityType.Key.TupleDescriptor.Count);
            var fields  = entityType.Columns
                          .Where(c => c.IsPrimaryKey)
                          .OrderBy(c => c.Field.MappingInfo.Offset)
                          .Select(c => FieldExpression.CreateField(c.Field, offset))
                          .ToList()
                          .AsReadOnly();

            return(new KeyExpression(entityType, fields, mapping, WellKnownMembers.IEntityKey, null, false));
        }
コード例 #14
0
        // Constructors

        private KeyExpression(
            TypeInfo entityType,
            System.Collections.ObjectModel.ReadOnlyCollection <FieldExpression> keyFields,
            Segment <int> segment,
            PropertyInfo underlyingProperty,
            ParameterExpression parameterExpression,
            bool defaultIfEmpty)
            : base(ExtendedExpressionType.Key, WellKnown.KeyFieldName, typeof(Key), segment, underlyingProperty, parameterExpression, defaultIfEmpty)
        {
            EntityType = entityType;
            KeyFields  = keyFields;
        }
コード例 #15
0
    public void BuildFields(TypeDef typeDef, TypeInfo typeInfo)
    {
      if (typeInfo.IsInterface) {
        var sourceFields = typeInfo.GetInterfaces()
          .SelectMany(i => i.Fields)
          .Where(f => !f.IsPrimaryKey && f.Parent == null);
        foreach (var srcField in sourceFields) {
          if (!typeInfo.Fields.Contains(srcField.Name))
            BuildInheritedField(typeInfo, srcField);
        }
      }
      else {
        var ancestor = typeInfo.GetAncestor();
        if (ancestor != null) {
          foreach (var srcField in ancestor.Fields.Where(f => !f.IsPrimaryKey && f.Parent == null)) {
            FieldDef fieldDef;
            if (typeDef.Fields.TryGetValue(srcField.Name, out fieldDef)) {
              if (fieldDef.UnderlyingProperty == null)
                throw new DomainBuilderException(
                  String.Format(Strings.ExFieldXIsAlreadyDefinedInTypeXOrItsAncestor, fieldDef.Name, typeInfo.Name));
              var getMethod = fieldDef.UnderlyingProperty.GetGetMethod()
                ?? fieldDef.UnderlyingProperty.GetGetMethod(true);
              if ((getMethod.Attributes & MethodAttributes.NewSlot) == MethodAttributes.NewSlot)
                BuildDeclaredField(typeInfo, fieldDef);
              else
                BuildInheritedField(typeInfo, srcField);
            }
            else
              BuildInheritedField(typeInfo, srcField);
          }
          foreach (var pair in ancestor.FieldMap)
            typeInfo.FieldMap.Add(pair.Key, typeInfo.Fields[pair.Value.Name]);
        }
      }

      foreach (var fieldDef in typeDef.Fields) {
        FieldInfo field;
        if (typeInfo.Fields.TryGetValue(fieldDef.Name, out field)) {
          if (field.ValueType!=fieldDef.ValueType)
            throw new DomainBuilderException(
              String.Format(Strings.ExFieldXIsAlreadyDefinedInTypeXOrItsAncestor, fieldDef.Name, typeInfo.Name));
        }
        else
          BuildDeclaredField(typeInfo, fieldDef);
      }
      typeInfo.Columns.AddRange(typeInfo.Fields.Where(f => f.Column!=null).Select(f => f.Column));

      if (typeInfo.IsEntity && !IsAuxiliaryType(typeInfo)) {
        foreach (var @interface in typeInfo.GetInterfaces())
          BuildFieldMap(@interface, typeInfo);
      }
    }
コード例 #16
0
        private static bool IsAuxiliaryType(TypeInfo type)
        {
            if (!type.IsEntity)
            {
                return(false);
            }

            var underlyingBaseType = type.UnderlyingType.BaseType;

            return(underlyingBaseType != null &&
                   underlyingBaseType.IsGenericType &&
                   underlyingBaseType.GetGenericTypeDefinition() == WellKnownOrmTypes.EntitySetItemOfT1T2);
        }
コード例 #17
0
        // Constructors

        public FieldAccessorProvider(TypeInfo typeInfo)
        {
            var fields = typeInfo.Fields;

            fieldAccessors = new FieldAccessor[fields.Count == 0 ? 0 : (fields.Max(field => field.FieldId) + 1)];
            foreach (var field in fields)
            {
                if (field.FieldId != FieldInfo.NoFieldId)
                {
                    fieldAccessors[field.FieldId] = CreateFieldAccessor(field);
                }
            }
        }
コード例 #18
0
    private void BuildInheritedField(TypeInfo type, FieldInfo inheritedField)
    {
      BuildLog.Info(Strings.LogBuildingInheritedFieldXY, type.Name, inheritedField.Name);
      var field = inheritedField.Clone();
      type.Fields.Add(field);
      field.ReflectedType = type;
      field.DeclaringType = inheritedField.DeclaringType;
      field.IsInherited = true;

      BuildNestedFields(inheritedField, field, inheritedField.Fields);

      if (inheritedField.Column!=null)
        field.Column = BuildInheritedColumn(field, inheritedField.Column);
    }
コード例 #19
0
 /// <summary>
 ///   Initializes a new instance of this class.
 /// </summary>
 /// <param name="data">Underlying <see cref="Tuple"/> value.</param>
 protected Structure(Tuple data)
 {
     try {
         typeInfo = GetTypeInfo();
         tuple    = data;
         SystemBeforeInitialize(false);
     }
     catch (Exception error) {
         InitializationError(GetType(), error);
         // GetType() call is correct here: no code will be executed further,
         // if base constructor will fail, but since descendant's constructor is aspected,
         // we must "simulate" its own call of InitializationError method.
         throw;
     }
 }
コード例 #20
0
        public Entity Materialize(int entityIndex, int typeIdIndex, TypeInfo type, Pair <int>[] entityColumns, Tuple tuple)
        {
            var result = entities[entityIndex];

            if (result != null)
            {
                return(result);
            }

            TypeReferenceAccuracy accuracy;
            int typeId = EntityDataReader.ExtractTypeId(type, typeIdRegistry, tuple, typeIdIndex, out accuracy);

            if (typeId == TypeInfo.NoTypeId)
            {
                return(null);
            }

            bool canCache            = accuracy == TypeReferenceAccuracy.ExactType;
            var  materializationInfo = MaterializationContext.GetTypeMapping(entityIndex, type, typeId, entityColumns);
            Key  key;
            var  keyIndexes = materializationInfo.KeyIndexes;

            if (!KeyFactory.IsValidKeyTuple(tuple, keyIndexes))
            {
                return(null);
            }
            if (keyIndexes.Length <= WellKnown.MaxGenericKeyLength)
            {
                key = KeyFactory.Materialize(Session.Domain, Session.StorageNodeId, materializationInfo.Type, tuple, accuracy, canCache, keyIndexes);
            }
            else
            {
                var keyTuple = materializationInfo.KeyTransform.Apply(TupleTransformType.TransformedTuple, tuple);
                key = KeyFactory.Materialize(Session.Domain, Session.StorageNodeId, materializationInfo.Type, keyTuple, accuracy, canCache, null);
            }
            if (accuracy == TypeReferenceAccuracy.ExactType)
            {
                var entityTuple = materializationInfo.Transform.Apply(TupleTransformType.Tuple, tuple);
                var entityState = Session.Handler.UpdateState(key, entityTuple);
                result = entityState.Entity;
            }
            else
            {
                result = Session.Query.SingleOrDefault(key);
            }
            entities[entityIndex] = result;
            return(result);
        }
コード例 #21
0
        public void CheckAssociations()
        {
            TypeInfo typeA = Domain.Model.Types[typeof(A)];

            Assert.IsNotNull(typeA);
            CheckAssociations(typeA.GetTargetAssociations(), 6, Multiplicity.ManyToMany, Multiplicity.ManyToOne, Multiplicity.OneToMany, Multiplicity.OneToOne, Multiplicity.ZeroToMany, Multiplicity.ZeroToOne);

            TypeInfo typeB = Domain.Model.Types[typeof(B)];

            Assert.IsNotNull(typeB);
            CheckAssociations(typeB.GetTargetAssociations(), 6, Multiplicity.ManyToMany, Multiplicity.ManyToOne, Multiplicity.OneToMany, Multiplicity.OneToOne, Multiplicity.ZeroToMany, Multiplicity.ZeroToOne);

            TypeInfo typeC = Domain.Model.Types[typeof(C)];

            Assert.IsNotNull(typeC);
            CheckAssociations(typeC.GetTargetAssociations(), 8, Multiplicity.ManyToMany, Multiplicity.ManyToOne, Multiplicity.OneToMany, Multiplicity.OneToOne, Multiplicity.ZeroToMany, Multiplicity.ZeroToOne);
        }
コード例 #22
0
        protected Operation(QueryProvider queryProvider)
        {
            QueryProvider = queryProvider;
            Type entityType = typeof(T);

            Session       = queryProvider.Session;
            DomainHandler = Session.Domain.Services.Get <DomainHandler>();
            TypeInfo      =
                queryProvider.Session.Domain.Model.Hierarchies.SelectMany(a => a.Types).Single(
                    a => a.UnderlyingType == entityType);
            var mapping = Session.StorageNode.Mapping;

            PrimaryIndexes = TypeInfo.AffectedIndexes
                             .Where(i => i.IsPrimary)
                             .Select(i => new PrimaryIndexMapping(i, mapping[i.ReflectedType]))
                             .ToArray();
            QueryBuilder = Session.Services.Get <QueryBuilder>();
        }
コード例 #23
0
 /// <summary>
 /// Initializes a new instance of this class.
 /// Used internally to initialize the structure on materialization.
 /// </summary>
 /// <param name="owner">The owner of this instance.</param>
 /// <param name="field">The owner field that describes this instance.</param>
 protected Structure(Persistent owner, FieldInfo field)
     : base(owner.Session)
 {
     try {
         typeInfo = GetTypeInfo();
         Owner    = owner;
         Field    = field;
         if (owner == null || field == null)
         {
             tuple = typeInfo.TuplePrototype.Clone();
         }
         else
         {
             tuple = field.ExtractValue(
                 new ReferencedTuple(() => Owner.Tuple));
         }
         SystemBeforeInitialize(true);
         InitializeOnMaterialize();
     }
     catch (Exception error) {
         InitializationErrorOnMaterialize(error);
         throw;
     }
 }
コード例 #24
0
        // Constructors

        private KeyExpression(
            TypeInfo entityType,
            IReadOnlyList <FieldExpression> keyFields,
            in Segment <int> segment,
コード例 #25
0
        private KeyInfo BuildKeyInfo(TypeInfo root, HierarchyDef hierarchyDef)
        {
            var keyFields = root.Fields
                            .Where(field => field.IsPrimaryKey)
                            .OrderBy(field => field.MappingInfo.Offset)
                            .ToList();

            var keyColumns = keyFields
                             .Where(field => field.Column != null)
                             .Select(field => field.Column)
                             .ToList();

            var keyTupleDescriptor = TupleDescriptor.Create(
                keyColumns.Select(c => c.ValueType).ToArray(keyColumns.Count));
            var typeIdColumnIndex = -1;

            if (hierarchyDef.IncludeTypeId)
            {
                for (var i = 0; i < keyColumns.Count; i++)
                {
                    if (keyColumns[i].Field.IsTypeId)
                    {
                        typeIdColumnIndex = i;
                    }
                }
            }

            var key           = new KeyInfo(root.Name, keyFields, keyColumns, keyTupleDescriptor, typeIdColumnIndex);
            var generatorKind = hierarchyDef.KeyGeneratorKind;

            // Force absence of key generator if key is a reference.
            if (key.ContainsForeignKeys)
            {
                generatorKind = KeyGeneratorKind.None;
            }

            if (generatorKind == KeyGeneratorKind.Default)
            {
                var canBeHandled = key.SingleColumnType != null && KeyGeneratorFactory.IsSupported(key.SingleColumnType);
                // Force absence of key generator if key can not be handled by standard keygen.
                if (!canBeHandled)
                {
                    generatorKind = KeyGeneratorKind.None;
                }
            }

            if (generatorKind == KeyGeneratorKind.None)
            {
                // No key generator is attached.
                // Each hierarchy has it's own equality identifier.
                key.IsFirstAmongSimilarKeys = true;
                key.EqualityIdentifier      = new object();
                return(key);
            }

            // Hierarchy has key generator.

            // Setup key generator name.
            key.GeneratorKind     = generatorKind;
            key.GeneratorBaseName = context.NameBuilder.BuildKeyGeneratorBaseName(key, hierarchyDef);
            key.GeneratorName     = context.NameBuilder.BuildKeyGeneratorName(key, hierarchyDef);
            var generatorIdentity = context.Configuration.MultidatabaseKeys
        ? key.GeneratorBaseName
        : key.GeneratorName;

            // Equality identifier is the same if and only if key generator names match.
            key.IsFirstAmongSimilarKeys = !processedKeyGenerators.Contains(key.GeneratorName);
            if (key.IsFirstAmongSimilarKeys)
            {
                _ = processedKeyGenerators.Add(key.GeneratorName);
            }

            if (keyEqualityIdentifiers.TryGetValue(generatorIdentity, out var equalityIdentifier))
            {
                key.EqualityIdentifier = equalityIdentifier;
            }
            else
            {
                key.EqualityIdentifier = new object();
                keyEqualityIdentifiers.Add(generatorIdentity, key.EqualityIdentifier);
            }

            // Don't create sequences for user key generators
            // and for key generators that are not sequence-backed (such as GuidGenerator).
            if (key.GeneratorKind == KeyGeneratorKind.Custom || !IsSequenceBacked(key))
            {
                return(key);
            }

            // Generate backing sequence.
            if (sequences.TryGetValue(key.GeneratorName, out var sequence))
            {
                key.Sequence = sequence;
            }
            else
            {
                var newSequence = BuildSequence(hierarchyDef, key);
                if (context.Configuration.MultidatabaseKeys)
                {
                    EnsureSequenceSeedIsUnique(newSequence);
                }

                key.Sequence = newSequence;
                sequences.Add(key.GeneratorName, key.Sequence);
            }

            return(key);
        }
コード例 #26
0
        /// <summary>
        /// Builds the <see cref="TypeInfo"/> instance, its key fields and <see cref="HierarchyInfo"/> for hierarchy root.
        /// </summary>
        /// <param name="typeDef"><see cref="TypeDef"/> instance.</param>
        public TypeInfo BuildType(TypeDef typeDef)
        {
            using (BuildLog.InfoRegion(Strings.LogBuildingX, typeDef.UnderlyingType.GetShortName())) {
                var typeInfo = new TypeInfo(context.Model, typeDef.Attributes)
                {
                    UnderlyingType  = typeDef.UnderlyingType,
                    Name            = typeDef.Name,
                    MappingName     = typeDef.MappingName,
                    MappingDatabase = typeDef.MappingDatabase,
                    MappingSchema   = typeDef.MappingSchema,
                    HasVersionRoots = typeDef.UnderlyingType.GetInterfaces().Any(type => type == typeof(IHasVersionRoots)),
                    Validators      = typeDef.Validators,
                };

                if (typeInfo.IsEntity && DeclaresOnValidate(typeInfo.UnderlyingType))
                {
                    typeInfo.Validators.Add(new EntityValidator());
                }

                if (typeDef.StaticTypeId != null)
                {
                    typeInfo.TypeId = typeDef.StaticTypeId.Value;
                }

                context.Model.Types.Add(typeInfo);

                // Registering connections between type & its ancestors
                var node = context.DependencyGraph.TryGetNode(typeDef);
                if (node != null)
                {
                    foreach (var edge in node.OutgoingEdges.Where(e =>
                                                                  e.Kind == EdgeKind.Implementation || e.Kind == EdgeKind.Inheritance))
                    {
                        var baseType = context.Model.Types[edge.Head.Value.UnderlyingType];
                        switch (edge.Kind)
                        {
                        case EdgeKind.Inheritance:
                            context.Model.Types.RegisterInheritance(baseType, typeInfo);
                            break;

                        case EdgeKind.Implementation:
                            context.Model.Types.RegisterImplementation(baseType, typeInfo);
                            break;
                        }
                    }
                }

                if (typeDef.IsEntity)
                {
                    var hierarchyDef = context.ModelDef.FindHierarchy(typeDef);

                    // Is type a hierarchy root?
                    if (typeInfo.UnderlyingType == hierarchyDef.Root.UnderlyingType)
                    {
                        foreach (var keyField in hierarchyDef.KeyFields)
                        {
                            var fieldInfo = BuildDeclaredField(typeInfo, typeDef.Fields[keyField.Name]);
                            fieldInfo.IsPrimaryKey = true;
                        }

                        typeInfo.Hierarchy = BuildHierarchyInfo(typeInfo, hierarchyDef);
                    }
                    else
                    {
                        var root = context.Model.Types[hierarchyDef.Root.UnderlyingType];
                        typeInfo.Hierarchy = root.Hierarchy;
                        foreach (var fieldInfo in root.Fields.Where(f => f.IsPrimaryKey && f.Parent == null))
                        {
                            BuildInheritedField(typeInfo, fieldInfo);
                        }
                    }
                }
                else if (typeDef.IsInterface)
                {
                    var hierarchyDef = context.ModelDef.FindHierarchy(typeDef.Implementors[0]);
                    foreach (var keyField in hierarchyDef.KeyFields)
                    {
                        var fieldInfo = BuildDeclaredField(typeInfo, typeDef.Fields[keyField.Name]);
                        fieldInfo.IsPrimaryKey = true;
                    }
                }

                return(typeInfo);
            }
        }
コード例 #27
0
        private FieldInfo BuildDeclaredField(TypeInfo type, FieldDef fieldDef)
        {
            BuildLog.Info(Strings.LogBuildingDeclaredFieldXY, type.Name, fieldDef.Name);

            var fieldInfo = new FieldInfo(type, fieldDef.Attributes)
            {
                UnderlyingProperty = fieldDef.UnderlyingProperty,
                Name         = fieldDef.Name,
                OriginalName = fieldDef.Name,
                MappingName  = fieldDef.MappingName,
                ValueType    = fieldDef.ValueType,
                ItemType     = fieldDef.ItemType,
                Length       = fieldDef.Length,
                Scale        = fieldDef.Scale,
                Precision    = fieldDef.Precision,
                Validators   = fieldDef.Validators,
            };

            if (fieldInfo.IsStructure && DeclaresOnValidate(fieldInfo.ValueType))
            {
                fieldInfo.Validators.Add(new StructureFieldValidator());
            }

            if (fieldInfo.IsEntitySet && DeclaresOnValidate(fieldInfo.ValueType))
            {
                fieldInfo.Validators.Add(new EntitySetFieldValidator());
            }

            type.Fields.Add(fieldInfo);

            if (fieldInfo.IsEntitySet)
            {
                AssociationBuilder.BuildAssociation(context, fieldDef, fieldInfo);
                return(fieldInfo);
            }

            if (fieldInfo.IsEntity)
            {
                var fields = context.Model.Types[fieldInfo.ValueType].Fields.Where(f => f.IsPrimaryKey);
                // Adjusting default value if any
                if (fields.Count() == 1 && fieldDef.DefaultValue != null)
                {
                    fieldInfo.DefaultValue =
                        ValueTypeBuilder.AdjustValue(fieldInfo, fields.First().ValueType, fieldDef.DefaultValue);
                }

                BuildNestedFields(null, fieldInfo, fields);

                if (!IsAuxiliaryType(type))
                {
                    AssociationBuilder.BuildAssociation(context, fieldDef, fieldInfo);
                    if (type.IsStructure)
                    {
                        fieldInfo.Associations.ForEach(a => context.DiscardedAssociations.Add(a));
                    }
                }

                // Adjusting type discriminator field for references
                if (fieldDef.IsTypeDiscriminator)
                {
                    type.Hierarchy.TypeDiscriminatorMap.Field = fieldInfo.Fields.First();
                }
            }

            if (fieldInfo.IsStructure)
            {
                BuildNestedFields(null, fieldInfo, context.Model.Types[fieldInfo.ValueType].Fields);
                var structureFullTextIndex = context.ModelDef.FullTextIndexes.TryGetValue(fieldInfo.ValueType);
                if (structureFullTextIndex != null)
                {
                    var hierarchyTypeInfo = context.Model.Types[fieldInfo.DeclaringType.UnderlyingType];
                    var structureTypeInfo = context.Model.Types[fieldInfo.ValueType];
                    var currentIndex      = context.ModelDef.FullTextIndexes.TryGetValue(hierarchyTypeInfo.UnderlyingType);
                    if (currentIndex == null)
                    {
                        currentIndex = new FullTextIndexDef(context.ModelDef.Types.TryGetValue(type.UnderlyingType));
                        context.ModelDef.FullTextIndexes.Add(currentIndex);
                    }

                    currentIndex.Fields.AddRange(structureFullTextIndex.Fields
                                                 .Select(f => new {
                        fieldInfo.DeclaringType
                        .StructureFieldMapping[new Pair <FieldInfo>(fieldInfo, structureTypeInfo.Fields[f.Name])].Name,
                        f.IsAnalyzed,
                        f.Configuration,
                        f.TypeFieldName
                    })
                                                 .Select(g => new FullTextFieldDef(g.Name, g.IsAnalyzed)
                    {
                        Configuration = g.Configuration, TypeFieldName = g.TypeFieldName
                    }));
                }
            }

            if (fieldInfo.IsPrimitive)
            {
                fieldInfo.DefaultValue         = fieldDef.DefaultValue;
                fieldInfo.DefaultSqlExpression = fieldDef.DefaultSqlExpression;
                fieldInfo.Column = BuildDeclaredColumn(fieldInfo);
                if (fieldDef.IsTypeDiscriminator)
                {
                    type.Hierarchy.TypeDiscriminatorMap.Field = fieldInfo;
                }
            }

            return(fieldInfo);
        }
コード例 #28
0
 /// <summary>
 /// Builds the name of the explicitly implemented field.
 /// </summary>
 /// <param name="type">The type of interface explicit member implements.</param>
 /// <param name="name">The member name.</param>
 /// <returns>Explicitly implemented field name.</returns>
 public string BuildExplicitFieldName(TypeInfo type, string name)
 {
     return(type.IsInterface ? type.UnderlyingType.Name + "." + name : name);
 }
コード例 #29
0
        /// <summary>
        /// Gets the name for <see cref="IndexDef"/> object.
        /// </summary>
        /// <param name="type">The type def.</param>
        /// <param name="index">The <see cref="IndexInfo"/> object.</param>
        /// <returns>Index name.</returns>
        public string BuildIndexName(TypeInfo type, IndexInfo index)
        {
            ArgumentValidator.EnsureArgumentNotNull(index, "index");
            if (!index.Name.IsNullOrEmpty())
            {
                return(index.Name);
            }

            string result = string.Empty;

            if (index.IsPrimary)
            {
                if (index.IsVirtual)
                {
                    var originIndex = index;
                    while (true)
                    {
                        var singleSourceIndex = (originIndex.Attributes & (IndexAttributes.Filtered | IndexAttributes.View | IndexAttributes.Typed)) != IndexAttributes.None;
                        if (singleSourceIndex)
                        {
                            var sourceIndex = originIndex.UnderlyingIndexes[0];
                            if (sourceIndex.ReflectedType != originIndex.ReflectedType)
                            {
                                originIndex = sourceIndex;
                                break;
                            }
                            originIndex = sourceIndex;
                        }
                        else
                        {
                            originIndex = null;
                            break;
                        }
                    }
                    result = originIndex != null
            ? string.Format("PK_{0}.{1}", type, originIndex.ReflectedType)
            : (type == index.DeclaringType
                ? string.Format("PK_{0}", type)
                : string.Format("PK_{0}.{1}", type, index.DeclaringType));
                }
                else
                {
                    result = index.DeclaringType != type
            ? string.Format("PK_{0}.{1}", type, index.DeclaringType)
            : string.Format("PK_{0}", type);
                }
            }
            else
            {
                if (!index.MappingName.IsNullOrEmpty())
                {
                    result = index.DeclaringType != type
            ? string.Format("{0}.{1}.{2}", type, index.DeclaringType, index.MappingName)
            : string.Format("{0}.{1}", type, index.MappingName);
                }
                else if (index.IsVirtual && index.DeclaringIndex.Name != null)
                {
                    result = index.DeclaringIndex.Name;
                }
                else
                {
                    var keyFields = new HashSet <FieldInfo>();
                    foreach (var keyColumn in index.KeyColumns.Keys)
                    {
                        var field = keyColumn.Field;
                        while (field.Parent != null && !field.Parent.IsStructure)
                        {
                            field = field.Parent;
                        }
                        keyFields.Add(field);
                    }
                    var indexNameSuffix = keyFields
                                          .Select(f => f.Name)
                                          .ToDelimitedString(String.Empty);
                    if (keyFields.Count == 1 && keyFields.Single().IsEntity)
                    {
                        result = index.DeclaringType != type
              ? string.Format("{0}.{1}.FK_{2}", type, index.DeclaringType, indexNameSuffix)
              : string.Format("{0}.FK_{1}", type, indexNameSuffix);
                    }
                    else
                    {
                        result = index.DeclaringType != type
              ? string.Format("{0}.{1}.IX_{2}", type, index.DeclaringType, indexNameSuffix)
              : string.Format("{0}.IX_{1}", type, indexNameSuffix);
                    }
                }
            }

            string suffix = string.Empty;

            if (index.IsVirtual)
            {
                if ((index.Attributes & IndexAttributes.Filtered) != IndexAttributes.None)
                {
                    suffix = ".FILTERED.";
                }
                else if ((index.Attributes & IndexAttributes.Join) != IndexAttributes.None)
                {
                    suffix = ".JOIN.";
                }
                else if ((index.Attributes & IndexAttributes.Union) != IndexAttributes.None)
                {
                    suffix = ".UNION.";
                }
                else if ((index.Attributes & IndexAttributes.View) != IndexAttributes.None)
                {
                    suffix = ".VIEW.";
                }
                else if ((index.Attributes & IndexAttributes.Typed) != IndexAttributes.None)
                {
                    suffix = ".TYPED.";
                }
                suffix += type.Name;
            }
            return(ApplyNamingRules(string.Concat(result, suffix)));
        }
コード例 #30
0
        /// <summary>
        /// Builds the name of the full-text index.
        /// </summary>
        /// <param name="typeInfo">The type info.</param>
        /// <returns>Index name.</returns>
        public string BuildFullTextIndexName(TypeInfo typeInfo)
        {
            var result = string.Format("FT_{0}", typeInfo.MappingName ?? typeInfo.Name);

            return(ApplyNamingRules(result));
        }