コード例 #1
0
ファイル: EntityMapper.cs プロジェクト: uQr/Visual-NHibernate
        public static ITable GetPrimaryTable(Entity entity)
        {
            var mappedTables = entity.MappedTables().ToList();

            if (mappedTables.Count == 0)
            {
                return null;
                //string msg = string.Format(
                //    "Entity {0} does not have a mapped table. It should not be included in the entities to be processed by the HBM file template",
                //    entity.Name);

                //Log.Error(msg);
                //throw new Exception(msg);
            }

            if (mappedTables.Count == 1)
            {
                return mappedTables[0];
            }

            foreach (ITable table in mappedTables)
            {
                // ReSharper disable AccessToModifiedClosure
                if (table.DirectedRelationships.All(r => r.FromTable == table))
                    // ReSharper restore AccessToModifiedClosure
                    return table;
            }

            return mappedTables[0];
        }
コード例 #2
0
ファイル: Utility.cs プロジェクト: uQr/Visual-NHibernate
        public static bool IsEntityMappedToTables(Entity entity)
        {
            if (entity.MappedTables().Count() > 0)
                return true;

            // Skip if the entity has no mapped tables;
            if (!entity.HasParent && !entity.HasChildren)
                return false;

            if (entity.HasParent)
            {
                if (EntityImpl.DetermineInheritanceTypeWithParent(entity) == EntityImpl.InheritanceType.TablePerClassHierarchy)
                    return entity.Parent.MappedTables().Count() > 0;
                else
                    return false;
            }
            else if (entity.IsAbstract && entity.HasChildren)
                return true;

            return false;
            // Entity has children
            //if (entity.IsAbstract)
        }
コード例 #3
0
ファイル: EntityMapper.cs プロジェクト: uQr/Visual-NHibernate
        public @class ProcessEntity(Entity entity)
        {
            Log.DebugFormat("Processing entity {0}", entity.Name);
            var newClass = new @class { name = entity.Name };
            IList<ITable> mappedTables = entity.MappedTables().ToList();
            // One Entity to one or more tables
            ITable table = GetPrimaryTable(entity);

            if (table != null && !string.IsNullOrEmpty(table.Name))
                newClass.table = table.Name.BackTick();

            if (table != null && !string.IsNullOrEmpty(table.Schema))
                newClass.schema = table.Schema.BackTick();

            var entityDefaultLazy = entity.GetEntityLazy();

            if (entity.GetEntityLazy() == Interfaces.NHibernateEnums.EntityLazyTypes.inherit_default)
                newClass.lazy = ArchAngel.Interfaces.SharedData.CurrentProject.GetProjectDefaultLazy();
            else
                newClass.lazy = entityDefaultLazy == Interfaces.NHibernateEnums.EntityLazyTypes.@true;

            newClass.lazySpecified = !newClass.lazy;

            newClass.batchsize = entity.GetEntityBatchSize();
            newClass.batchsizeSpecified = entity.GetEntityBatchSize() != 1;

            if (entity.GetEntityDynamicInsert())
                newClass.dynamicinsert = true;

            if (entity.GetEntityDynamicUpdate())
                newClass.dynamicupdate = true;

            newClass.@abstract = entity.IsAbstract;

            if (entity.IsAbstract)
                newClass.abstractSpecified = true;

            newClass.mutable = entity.GetEntityMutable();
            newClass.optimisticlock = (optimisticLockMode)Enum.Parse(typeof(optimisticLockMode), entity.GetEntityOptimisticLock().ToString(), true);
            newClass.selectbeforeupdate = entity.GetEntitySelectBeforeUpdate();

            if (entity.Cache.Usage != Cache.UsageTypes.None)
            {
                newClass.cache = new cache()
                {
                    include = (cacheInclude)Enum.Parse(typeof(cacheInclude), entity.Cache.Include.ToString().Replace("_", ""), true),
                    region = entity.Cache.Region
                };
                switch (entity.Cache.Usage)
                {
                    case Cache.UsageTypes.NonStrict_Read_Write:
                        newClass.cache.usage = cacheUsage.nonstrictreadwrite;
                        break;
                    case Cache.UsageTypes.Read_Only:
                        newClass.cache.usage = cacheUsage.@readonly;
                        break;
                    case Cache.UsageTypes.Read_Write:
                        newClass.cache.usage = cacheUsage.readwrite;
                        break;
                    case Cache.UsageTypes.Transactional:
                        newClass.cache.usage = cacheUsage.transactional;
                        break;
                    default:
                        throw new NotImplementedException("This cache type not implemented yet: " + entity.Cache.Usage.ToString());
                }
            }

            if (entity.GetEntityBatchSize() != 1)
                newClass.batchsize = entity.GetEntityBatchSize();

            if (!string.IsNullOrWhiteSpace(entity.GetEntityProxy()))
                newClass.proxy = entity.GetEntityProxy();

            if (!string.IsNullOrWhiteSpace(entity.GetEntityPersister()))
                newClass.persister = entity.GetEntityPersister();

            string sqlWhere = entity.GetEntitySqlWhereClause();

            if (!string.IsNullOrEmpty(sqlWhere))
                newClass.where = sqlWhere;

            // bool isSingleColumnPK = false;

            if (entity.IsAbstract)
            {
                // This is an abstract class in Table Per Concrete Class inheritance. The child entities
                // should have properties of the same name.
                Entity firstChild = entity.Children.FirstOrDefault();

                while (firstChild != null && firstChild.IsAbstract)
                    firstChild = firstChild.Children.FirstOrDefault();

                if (firstChild != null)
                {
                    ITable childTable = GetPrimaryTable(firstChild);
                    ProcessEntityKey(firstChild, newClass, childTable);
                    // isSingleColumnPK = childTable.ColumnsInPrimaryKey.Count() == 1;

                    foreach (var property in entity.Properties.OrderBy(p => p.Name))
                    {
                        if (firstChild.PropertiesHiddenByAbstractParent.Single(p => p.Name == property.Name).IsKeyProperty)
                            continue;

                        var mappedColumn = firstChild.PropertiesHiddenByAbstractParent.Single(p => p.Name == property.Name).MappedColumn();
                        property prop = new property { name = property.Name, column = mappedColumn.Name.BackTick() };
                        //AddExtraInfoToProperty(prop, property);
                        newClass.AddProperty(prop);
                    }
                }
                foreach (Entity child in entity.Children)
                {
                    Entity theChild = child;

                    while (theChild != null && theChild.IsAbstract)
                        theChild = theChild.Children.FirstOrDefault();

                    ITable mappedTable = theChild.MappedTables().First();

                    unionsubclass union = new unionsubclass()
                    {
                        name = theChild.Name,
                        table = mappedTable.Name.BackTick()
                    };
                    newClass.AddItem1(union);

                    List<property> unionProperties = new List<property>();

                    foreach (Property prop in theChild.ConcreteProperties)
                    {
                        if (prop.IsKeyProperty)
                            continue;

                        unionProperties.Add(
                        new property()
                        {
                            name = prop.Name,
                            column = prop.MappedColumn().Name.BackTick()
                        });
                        //AddExtraInfoToProperty(prop, property);
                    }
                    union.Items = unionProperties.ToArray();
                }
            }
            else
            {
                ProcessEntityKey(entity, newClass, table);
                // isSingleColumnPK = table.ColumnsInPrimaryKey.Count() == 1;
            }
            var propertiesAlreadyHandled = new List<Property>();

            foreach (ITable joinedTable in mappedTables.OrderBy(t => t.Name))
            {
                if (joinedTable == table)
                    continue;

                join joinNode = new join();
                joinNode.table = joinedTable.Name.BackTick();
                joinNode.schema = joinedTable.Schema.BackTick();
                int numPrimaryKeyColumns = joinedTable.ColumnsInPrimaryKey.Count();

                if (numPrimaryKeyColumns > 0)
                {
                    key keyNode = GetKeyNode(joinedTable);
                    joinNode.key = keyNode;
                }

                foreach (var property in entity.Properties.OrderBy(p => p.Name))
                {
                    var mappedColumn = property.MappedColumn();

                    if (mappedColumn == null || mappedColumn.Parent != joinedTable)
                        continue;

                    property prop = new property { name = property.Name, column = mappedColumn.Name.BackTick() };
                    AddExtraInfoToProperty(prop, property);
                    joinNode.AddProperty(prop);
                    propertiesAlreadyHandled.Add(property);
                }
                newClass.AddItem1(joinNode);
            }
            var versionProperty = entity.Properties.FirstOrDefault(p => p.GetPropertyIsVersion());

            if (versionProperty != null)
            {
                version versionNode = new version();
                versionNode.column1 = versionProperty.MappedColumn().Name.BackTick();
                versionNode.name = versionProperty.Name;
                versionNode.type = versionProperty.NHibernateType;
                // AddExtraInfoToProperty(prop, property);
                newClass.SetVersion(versionNode);
                propertiesAlreadyHandled.Add(versionProperty);
            }

            //foreach (var prop in ProcessProperties(entity.Properties.Except(propertiesAlreadyHandled).Except(entity.ForeignKeyPropertiesToExclude), isSingleColumnPK).OrderBy(p => p.name))
            foreach (var prop in ProcessProperties(entity.Properties.Except(propertiesAlreadyHandled).Except(entity.ForeignKeyPropertiesToExclude)).OrderBy(p => p.name))
                newClass.AddProperty(prop);

            // Process components, skip component used as Key.
            foreach (var component in ProcessComponent(entity.Components.Except(new[] { entity.Key.Component })).OrderBy(c => c.name))
                newClass.AddComponent(component);

            ProcessInheritance(entity, newClass);

            var referenceMapper = new ReferenceMapper();
            referenceMapper.ProcessReferences(entity, item => newClass.AddItem(item));
            return newClass;
        }
コード例 #4
0
ファイル: EntityLoader.cs プロジェクト: uQr/Visual-NHibernate
        private void ProcessJoinedSubclasses(MappingSet mappingSet, IDatabase database, EntitySet entities, Entity newEntity, IEnumerable<joinedsubclass> joinedsubclasses, ParseResults results, string unqualifiedNamespace)
        {
            if (joinedsubclasses == null) return;

            ITable parentTable = null;

            if (newEntity.MappedTables().Count() > 0)
                parentTable = newEntity.MappedTables().ElementAt(0);

            foreach (joinedsubclass hSubclass in joinedsubclasses)
            {
                Entity childEntity;
                string @namespace;
                string name;

                if (IsNameFullyQualified(hSubclass.name, out @namespace, out name))
                {
                    childEntity = new EntityImpl(name);

                    string currentNamespace = ArchAngel.Interfaces.SharedData.CurrentProject.GetUserOption("ProjectNamespace") == null ? "" : ArchAngel.Interfaces.SharedData.CurrentProject.GetUserOption("ProjectNamespace").ToString();

                    if (string.IsNullOrWhiteSpace(currentNamespace))
                        ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("ProjectNamespace", @namespace);

                    unqualifiedNamespace = @namespace;
                }
                else
                    childEntity = new EntityImpl(hSubclass.name);

                childEntity.SetEntityLazy(hSubclass.lazy);
                newEntity.AddChild(childEntity);

                var childTableMapping = new MappingImpl();
                ITable subClassTable;

                if (!string.IsNullOrEmpty(hSubclass.table))
                {
                    string schema = "";

                    if (!string.IsNullOrEmpty(hSubclass.schema))
                        schema = hSubclass.schema;
                    else if (parentTable != null)
                        schema = parentTable.Schema;

                    subClassTable = database.GetTable(hSubclass.table.UnBackTick(), schema.UnBackTick());
                    subClassTable.Database = database;
                }
                else
                    subClassTable = parentTable;

                childTableMapping.FromTable = subClassTable;
                childTableMapping.ToEntity = childEntity;

                foreach (var hProperty in hSubclass.Properties())
                {
                    var property = CreateProperty(childEntity, childTableMapping, hProperty);
                    SetPropertyInfoFromParsedCode(property, results, unqualifiedNamespace, childTableMapping.FromTable.Schema, hSubclass.name);
                }
                if (hSubclass.key != null)
                {
                    string keyColumnName;

                    if (!string.IsNullOrEmpty(hSubclass.key.column1))
                        keyColumnName = hSubclass.key.column1;
                    else //if (hSubclass.key.column != null && hSubclass.key.column.Count() > 0)
                        keyColumnName = hSubclass.key.column[0].name;

                    Property keyProp = childEntity.Properties.FirstOrDefault(p => p.MappedColumn() != null && p.MappedColumn().Name == keyColumnName);

                    if (keyProp == null)
                    {
                        keyProp = CreateProperty(childEntity, childTableMapping, hSubclass.key, subClassTable);
                        SetPropertyInfoFromParsedCode(keyProp, results, unqualifiedNamespace, childTableMapping.FromTable.Schema, childEntity.Name);
                        keyProp.IsHiddenByAbstractParent = true;
                    }
                    keyProp.IsKeyProperty = true;
                }
                entities.AddEntity(childEntity);
                mappingSet.AddMapping(childTableMapping);

                ProcessJoinedSubclasses(mappingSet, database, entities, childEntity, hSubclass.joinedsubclass1, results, unqualifiedNamespace);
            }
        }
コード例 #5
0
ファイル: Entity.cs プロジェクト: uQr/Visual-NHibernate
        public void RemoveChild(Entity entity)
        {
            if (!children.Contains(entity))
                return;

            children.Remove(entity);
            entity.Parent = null;

            // Add the ID property back to the child entity
            for (int i = entity.Key.Properties.ToList().Count - 1; i >= 0; i--)
            {
                if (entity.Properties.Count(p => p == entity.Key.Properties.ElementAt(i)) == 0)
                    entity.AddProperty(entity.Key.Properties.ElementAt(i));
            }
            // Add any hidden properties back to the child
            foreach (var hiddenProperty in entity.PropertiesHiddenByAbstractParent)
                hiddenProperty.IsHiddenByAbstractParent = false;

            foreach (var hiddenProperty in entity.PropertiesInHiddenKey)
                hiddenProperty.IsPartOfHiddenKey = false;

            // Add references back between removed child and its parent, which was removed when creating the inheritance structure.
            if (entity.MappedTables().Count() > 0 && this.MappedTables().Count() > 0 &&
                entity.DirectedReferences.Count(d => d.ToEntity == this) == 0)
            {
                var thisTable = this.MappedTables().ElementAt(0);
                var childTable = entity.MappedTables().ElementAt(0);

                foreach (Relationship rel in thisTable.Relationships.Where(r => (r.ForeignTable == thisTable && r.PrimaryTable == childTable) || (r.ForeignTable == childTable && r.PrimaryTable == thisTable)))
                    ArchAngel.Providers.EntityModel.Controller.MappingLayer.MappingProcessor.ProcessRelationshipInternal(entity.EntitySet.MappingSet, rel, new ArchAngel.Providers.EntityModel.Controller.MappingLayer.OneToOneEntityProcessor());
            }
            ChildrenChanged.RaiseDeletionEventEx(this, entity);
        }
コード例 #6
0
ファイル: Entity.cs プロジェクト: uQr/Visual-NHibernate
        public static InheritanceType DetermineInheritanceTypeWithParent(Entity entity)
        {
            if (entity.Parent == null)
                return InheritanceType.None;
            else
            {
                List<ITable> parentMappedTables = entity.Parent.MappedTables().ToList();
                List<ITable> childMappedTables = entity.MappedTables().ToList();

                if (childMappedTables.Count == 1 && entity.Parent.IsAbstract && parentMappedTables.Count == 0)
                    return InheritanceType.TablePerConcreteClass;
                else if (childMappedTables.Count == 1 && parentMappedTables.Count == 1 &&
                    childMappedTables[0] == parentMappedTables[0])
                {
                    return InheritanceType.TablePerClassHierarchy;
                }
                else
                    return InheritanceType.TablePerSubClass;
                //return DetermineInheritanceTypeWithChildren(entity.Parent);
            }
        }
コード例 #7
0
ファイル: Entity.cs プロジェクト: uQr/Visual-NHibernate
        public static InheritanceType DetermineInheritanceTypeWithChildren(Entity entity)
        {
            int numChildren = entity.Children.Count();
            IList<ITable> mappedTables = entity.MappedTables().ToList();

            if (numChildren > 0)
            {
                if (mappedTables.Count == 1)
                {
                    if (entity.Children.All(e => e.MappedTables().Count() == 1 && e.MappedTables().First() == mappedTables[0]))
                    {
                        // All children mapped to the same table.
                        return InheritanceType.TablePerClassHierarchy;
                    }
                    return InheritanceType.TablePerSubClass;
                }
                if (mappedTables.Count == 0)
                {
                    // No mapping for parent class.
                    return InheritanceType.TablePerConcreteClass;
                }
                return InheritanceType.Unsupported;
            }
            return InheritanceType.None;
        }
コード例 #8
0
        private void PostProcessEntity(MappingSet set, Entity entity)
        {
            if (entity.HasParent == false) return;

            var childTable = entity.MappedTables().First();
            var parentTable = entity.Parent.MappedTables().First();

            // Create foreign key for parent relationship

            // This code makes a major assumption: That the primary key of the child has the same columns
            // as the primary key of the parent.
            var name = GetNextKeyName("FK_" + parentTable.Name + "_" + childTable.Name, set);
            var foreignKey = new Key(name, DatabaseKeyType.Foreign);
            var primaryKey = parentTable.FirstPrimaryKey;
            var childPrimaryKey = childTable.FirstPrimaryKey;
            foreignKey.ReferencedKey = primaryKey;
            childTable.AddKey(foreignKey);

            foreach (var column in childPrimaryKey.Columns)
            {
                foreignKey.AddColumn(column.Name);
            }
        }
コード例 #9
0
        private bool IsSelectionValidForEntityRequestor(Entity selectedEntity)
        {
            List<ITable> selectedEntitiesTables = selectedEntity.MappedTables().ToList();
            List<Relationship> validRelationships = new List<Relationship>();
            List<ITable> validAssociationTables = new List<ITable>();

            if (selectedEntitiesTables.Count == 1 &&
                Entity.MappedTables().Count() == 1 &&
                selectedEntitiesTables[0] == Entity.MappedTables().ElementAt(0))
            {
                // Table Per Hierarchy inheritance
                return true;
            }
            if (RequestorType == RequestorTypes.Entity_Select_Parent &&
                selectedEntitiesTables.Count == 0)
            {
                bool isOk = true;

                foreach (Property property in selectedEntity.Properties)
                {
                    if (Entity.Properties.Count(p => p.Name == property.Name && p.Type == property.Type) == 0)
                    {
                        isOk = false;
                        break;
                    }
                }
                // This is OK for Table Per Concrete Class inheritance - the Base is totally virtual and doesn't have
                // a mapped table in the database, and all of it's properties exist in the child class.
                if (isOk)
                    return true;
            }
            else if (RequestorType == RequestorTypes.Entity_Select_Child && selectedEntitiesTables.Count > 0)
            {
                bool isOk = true;

                foreach (Property property in Entity.Properties)
                {
                    if (selectedEntity.Properties.Count(p => p.Name == property.Name && p.Type == property.Type) == 0)
                    {
                        isOk = false;
                        break;
                    }
                }
                // This is OK for Table Per Concrete Class inheritance - the Base is totally virtual and doesn't have
                // a mapped table in the database, and all of it's properties exist in the child class.
                if (isOk)
                    return true;
            }
            if (SelectedRelationship != null)
                return true;

            // Check that a relationship or association table exists between the entity and the new selected entity
            foreach (ITable table in Entity.MappedTables())
            {
                foreach (Relationship relationship in table.Relationships)
                {
                    if (selectedEntitiesTables.Contains(relationship.PrimaryTable) ||
                        selectedEntitiesTables.Contains(relationship.ForeignTable))
                    {
                        validRelationships.Add(relationship);
                        SelectedRelationship = relationship;

                        if (table == relationship.PrimaryTable)
                        {
                            CardinalityPrimary = relationship.PrimaryCardinality;
                            CardinalityForeign = relationship.ForeignCardinality;
                        }
                        else
                        {
                            CardinalityPrimary = relationship.ForeignCardinality;
                            CardinalityForeign = relationship.PrimaryCardinality;
                        }
                        break;
                    }
                }
                if (SelectedRelationship != null)
                    break;
            }
            IKey primaryKey = null;
            IKey foreignKey = null;
            ITable associationTable = null;

            if (validRelationships.Count == 0)
                associationTable = Entity.GetAssociationTable(selectedEntity, out CardinalityPrimary, out CardinalityForeign, out primaryKey, out foreignKey);

            if (validRelationships.Count == 0 &&
                associationTable == null)
            {
                //MessageBox.Show(this, string.Format("No relationships or association tables exist between {0} and {1}.{2}You need to add a relationship (or association table) between the tables in the database, or add a virtual relationship between these tables in the table-diagrammer.",
                //    Entity.Name,
                //    selectedEntity.Name,
                //    Environment.NewLine), "No valid relationships", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                //Close();
                //return;
                return false;
            }
            if (associationTable != null)
                AssociationTable = associationTable;

            return true;
        }