コード例 #1
0
        public virtual void MapTypes(List <Type> allTypes, NHibernate.Cfg.Configuration cfg, Func <string, string> formatter)
        {
            var m = new HbmMapping();

            m.Items = allTypes.Select(t =>
            {
                var sc                = new HbmSubclass();
                sc.name               = GetName(t);
                sc.extends            = GetName(t.BaseType);
                sc.discriminatorvalue = map.GetOrCreateDefinition(t).Discriminator ?? t.Name;
                sc.lazy               = false;
                sc.lazySpecified      = true;

                var propertyMappings = GetPersistables(t)
                                       .Select(p => p.Attribute.GetPropertyMapping(p.DeclaringProperty, formatter))
                                       .ToList();
                if (propertyMappings.Count > 0)
                {
                    if (sc.Items == null)
                    {
                        sc.Items = propertyMappings.ToArray();
                    }
                    else
                    {
                        sc.Items = sc.Items.Union(propertyMappings).ToArray();
                    }
                }

                return(sc);
            }).ToArray();
            var dbg = m.AsString();

            cfg.AddDeserializedMapping(m, "N2");
        }
コード例 #2
0
        private static void ShowOutputXmlMappings(HbmMapping mapping)
        {
            var outputXmlMappings = mapping.AsString();

            Console.WriteLine(outputXmlMappings);
            File.WriteAllText(OutputXmlMappingsFile, outputXmlMappings);
        }
コード例 #3
0
 private static void ExportHbmMappingsXml(HbmMapping hbmMapping, string name, string exportPath)
 {
     using (TextWriter tw = new StreamWriter(File.Open(Path.Combine(exportPath, name + ".hbm.xml"), FileMode.Create, FileAccess.Write)))
     {
         tw.Write(hbmMapping.AsString());
     }
 }
コード例 #4
0
        public void XmlMapping()
        {
            IHbmMapping mapper     = new TestsSimpleModelMapper(new TestsMappingAssemblies());
            HbmMapping  hbmMapping = mapper.GetHbmMapping();

            if (hbmMapping != null)
            {
                Console.WriteLine(hbmMapping.AsString());
            }
        }
コード例 #5
0
        private void ShowOutputXmlMappings(HbmMapping mapping)
        {
            if (!ShowLogs)
            {
                return;
            }

            var output = mapping.AsString();

            Console.WriteLine(output);
        }
コード例 #6
0
        private void showOutputXmlMappings(HbmMapping mapping)
        {
            if (!ShowLogs)
            {
                return;
            }
            var outputXmlMappings = mapping.AsString();

            Console.WriteLine(outputXmlMappings);
            File.WriteAllText(OutputXmlMappingsFile, outputXmlMappings);
        }
コード例 #7
0
ファイル: ClassMappingTest.cs プロジェクト: hunghq/hbm2code
        private void LoadClassMappings(Configuration configuration)
        {
            var mapper = new ModelMapper();

            mapper.AddMappings(GetClassMappings());
            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            configuration.AddMapping(mapping);

            logger.WriteLine(mapping.AsString());
        }
コード例 #8
0
        private static void showOutputXmlMappings(HbmMapping mapping, bool showLogs, string outputXmlMappingsFile)
        {
            if (!showLogs)
            {
                return;
            }
            var outputXmlMappings = mapping.AsString();

            Console.WriteLine(outputXmlMappings);
            var path = Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), outputXmlMappingsFile);

            File.WriteAllText(path, outputXmlMappings);
        }
コード例 #9
0
        private void showOutputXmlMappings(HbmMapping mapping)
        {
            var outputXmlMappings = mapping.AsString();

            if (ShowLogs)
            {
                Console.WriteLine(outputXmlMappings);
            }
            if (OutputXmlMappingsFile == null)
            {
                return;
            }
            File.WriteAllText(OutputXmlMappingsFile, outputXmlMappings);
        }
コード例 #10
0
        static void MappingByCode()
        {
            Configuration cfg = new Configuration();

            cfg.Configure();

            var mapper = new ModelMapper();

            mapper.AddMapping(typeof(DoctorByCodeMapping));

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            //输出编译好的XML映射
            Trace.WriteLine(mapping.AsString());

            cfg.AddMapping(mapping);

            SessionFactory = cfg.BuildSessionFactory();
        }
コード例 #11
0
        public void ExclusionDemo()
        {
            var orm = new ObjectRelationalMapper();

            orm.Patterns.Poids.Add(new MyPoidProperty());             // <== recognize the property representing the POID

            IPatternsAppliersHolder patternsAppliers =
                (new CoolPatternsAppliersHolder(orm))
                .UnionWith(new MyTablesAndColumnsNamingPack());                         // <=== Note the usage of UnionWith instead Merge

            var mapper = new Mapper(orm, patternsAppliers);

            // The strategy to represent classes is not important
            orm.TablePerClass <PorBoxEO>();
            orm.TablePerClass <PorEO>();

            // Show the mapping to the console
            HbmMapping mapping =
                mapper.CompileMappingFor(new[] { typeof(PorEO), typeof(PorBoxEO) });

            Console.Write(mapping.AsString());
        }
コード例 #12
0
        public virtual void MapTypes(List <Type> allTypes, NHibernate.Cfg.Configuration cfg, Func <string, string> formatter)
        {
            var m = new HbmMapping();

            m.Items = allTypes.Select(t =>
            {
                var sc                = new HbmSubclass();
                sc.name               = GetName(t);
                sc.extends            = GetName(t.BaseType);
                sc.discriminatorvalue = map.GetOrCreateDefinition(t).Discriminator ?? t.Name;
                sc.lazy               = false;
                sc.lazySpecified      = true;

                var propertyMappings = GetPersistables(t)
                                       .Select(p => p.Attribute.GetPropertyMapping(p.DeclaringProperty, formatter))
                                       .ToList();
                if (propertyMappings.Count > 0)
                {
                    if (sc.Items == null)
                    {
                        sc.Items = propertyMappings.ToArray();
                    }
                    else
                    {
                        sc.Items = sc.Items.Union(propertyMappings).ToArray();
                    }
                }
                logger.DebugFormat("Generating subclass {0} with discriminator {1} extending {2} with {3} items ({4} property mappings)", sc.name, sc.discriminatorvalue, sc.extends, sc.Items != null ? sc.Items.Length.ToString() : "(null)", propertyMappings.Count);
                return(sc);
            }).ToArray();
            if (Debugger.IsAttached)
            {
                var dbg = m.AsString();
            }
            cfg.AddDeserializedMapping(m, "N2");
        }
コード例 #13
0
        public void ComposingPatternsAppliersPacks()
        {
            // Thanks to Lorenzo Vegetti to provide the domain of this example.
            // This example refers to a little-domain, interesting from the point of view of mapping with ConfORM.
            // Here you can see how apply general convetion, how and when compose patterns-appliers-packs and patterns-appliers,
            // how ConfORM can apply different mapping depending on the type of enum (see the difference on CostOptions) and so on...
            // You don't have to organize the mapping all in one class, as in this example, and you don't have to use the IModuleMapping...
            // You can organize the mapping as you feel more confortable for your application; in some case a class is enough, in other cases would
            // be better the separation per module/concern, you are not closed in "mapping per class" box.

            var orm = new ObjectRelationalMapper();

            // With the follow line I'm adding the pattern for the POID strategy ("native" instead the default "High-Low")
            orm.Patterns.PoidStrategies.Add(new NativePoidPattern());

            // composition of patterns-appliers-packs and patterns-appliers for Lorenzo's domain
            // Note: for bidirectional-one-to-many association Lorenzo is not interested in the default cascade behavior,
            // implemented in the BidirectionalOneToManyRelationPack, because he is using a sort of soft-delete in his base class VersionModelBase.
            // He can implements a custom pack of patterns-appliers to manage the situation when classes does not inherits from VersionModelBase by the way
            // he don't want the cascade atall, so the BidirectionalOneToManyInverseApplier will be enough
            IPatternsAppliersHolder patternsAppliers =
                (new SafePropertyAccessorPack())
                .Merge(new OneToOneRelationPack(orm))
                .Merge(new BidirectionalManyToManyRelationPack(orm))
                .Merge(new DiscriminatorValueAsClassNamePack(orm))
                .Merge(new CoolColumnsNamingPack(orm))
                .Merge(new TablePerClassPack())
                .Merge(new PluralizedTablesPack(orm, new EnglishInflector()))
                .Merge(new ListIndexAsPropertyPosColumnNameApplier())
                .Merge(new BidirectionalOneToManyInverseApplier(orm))
                .Merge(new EnumAsStringPack())
                .Merge(new DatePropertyByNameApplier())
                .Merge(new MsSQL2008DateTimeApplier());

            // Instancing the Mapper using the result of Merge
            var mapper = new Mapper(orm, patternsAppliers);

            // Setting the version property using the base class
            orm.VersionProperty <VersionModelBase>(v => v.Version);

            // Note: I'm declaring the strategy only for the base entity
            orm.TablePerClassHierarchy <Cost>();
            orm.TablePerClass <EditionQuotation>();
            orm.TablePerClass <ProductQuotation>();
            orm.TablePerClass <Quotation>();

            AppliesGeneralConventions(mapper);

            // EditionQuotation.PrintCost don't use lazy-loading
            mapper.Customize <EditionQuotation>(map => map.ManyToOne(eq => eq.PrintCost, m2o => m2o.Lazy(LazyRelation.NoLazy)));

            // Customizes some others DDL's stuff outside conventions
            CustomizeColumns(mapper);

            // Note : I have to create mappings for the whole domain
            HbmMapping mapping =
                mapper.CompileMappingFor(
                    typeof(GenericModelBase <>).Assembly.GetTypes().Where(t => t.Namespace == typeof(GenericModelBase <>).Namespace));

            Console.Write(mapping.AsString());
        }
コード例 #14
0
 public static void ShowInConsole(this HbmMapping mapping)
 {
     Console.WriteLine(mapping.AsString());
 }
コード例 #15
0
        public void Compile(NHcfg.Configuration configuration)
        {
            var mapper = new ModelMapperWithNamingConventions();

            mapper.IsEntity((type, declared) => MappingHelper.IsEntity(type));
            mapper.IsRootEntity((type, declared) => MappingHelper.IsRootEntity(type));
            mapper.IsTablePerClass((type, declared) =>
            {
                var discriminator = MappingHelper.GetDiscriminatorColumn(type);
                return(string.IsNullOrWhiteSpace(discriminator));
            });
            mapper.IsTablePerClassHierarchy((type, declared) =>
            {
                var discriminator = MappingHelper.GetDiscriminatorColumn(type);
                return(!string.IsNullOrWhiteSpace(discriminator));
            });
            mapper.IsTablePerConcreteClass((type, declared) => false);

            mapper.IsOneToMany((mi, declared) =>
            {
                if (Attribute.IsDefined(mi, (typeof(ManyToManyAttribute))))
                {
                    return(false);
                }

                return(declared || _defaultMapper.ModelInspector.IsOneToMany(mi));
            });

            mapper.IsManyToMany((mi, declared) =>
            {
                if (Attribute.IsDefined(mi, (typeof(ManyToManyAttribute))))
                {
                    return(true);
                }

                return(declared || _defaultMapper.ModelInspector.IsManyToAny(mi));
            });

            mapper.IsPersistentProperty((mi, declared) =>
            {
                if (!NhMappingHelper.IsPersistentProperty(mi))
                {
                    return(false);
                }

                return(_defaultMapper.ModelInspector.IsPersistentProperty(mi));
            });

            mapper.BeforeMapSubclass += (modelInspector, type, subclassCustomizer) =>
            {
                var discriminatorValue = MappingHelper.GetDiscriminatorValue(type);

                subclassCustomizer.DiscriminatorValue(discriminatorValue);


                var joinPropAttribute = type.GetAttribute <JoinedPropertyAttribute>();
                if (joinPropAttribute != null)
                {
                    if (string.IsNullOrWhiteSpace(joinPropAttribute.TableName))
                    {
                        throw new Exception($"{nameof(JoinedPropertyAttribute.TableName)} is mandatory for `{joinPropAttribute.GetType().Name}`, check class `{type.FullName}`");
                    }

                    if (subclassCustomizer is NMIMPL.SubclassMapper subclassMapper)
                    {
                        // add join with provided table name, all properties will be added using current conventions and placed to the corresponding group using SplitGroupId = TableName
                        subclassMapper.Join(joinPropAttribute.TableName, j =>
                        {
                            j.Table(joinPropAttribute.TableName);

                            j.Fetch(FetchKind.Join);

                            j.Key(k =>
                            {
                                k.Column("Id");
                            });
                        });
                    }
                }
            };

            mapper.SplitsFor((type, definedSplits) =>
            {
                var splits = definedSplits.ToList();

                if (type.Name.Contains("TestProcessConfiguration"))
                {
                }

                var joinPropAttribute = type.GetAttribute <JoinedPropertyAttribute>();
                if (joinPropAttribute != null && !splits.Contains(joinPropAttribute.TableName))
                {
                    splits.Add(joinPropAttribute.TableName);
                }

                return(splits);
            });

            mapper.IsTablePerClassSplit((definition, b) => true);

            mapper.BeforeMapElement += (modelInspector, member, collectionRelationElementCustomizer) =>
            {
            };

            mapper.BeforeMapProperty += (modelInspector, member, propertyCustomizer) =>
            {
                var propertyType = member.LocalMember.GetPropertyOrFieldType();

                var    columnName = MappingHelper.GetColumnName(member.LocalMember);
                string sqlType    = null;
                IType  columnType = null;

                if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
                {
                    columnType = NHibernateUtil.DateTime;
                    sqlType    = "DateTime";
                }
                else
                if (member.LocalMember.GetAttribute <StringLengthAttribute>()?.MaximumLength == int.MaxValue)
                //if (Attribute.IsDefined(member.LocalMember, (typeof(StringClobAttribute))))
                {
                    columnType = NHibernateUtil.StringClob;
                    sqlType    = "nvarchar(max)";
                }

                if (columnType != null)
                {
                    propertyCustomizer.Type(columnType);
                }

                if (Attribute.GetCustomAttribute(member.LocalMember, typeof(ReadonlyPropertyAttribute), true) is ReadonlyPropertyAttribute readonlyAttribute)
                {
                    propertyCustomizer.Insert(readonlyAttribute.Insert);
                    propertyCustomizer.Update(readonlyAttribute.Update);
                }

                propertyCustomizer.Column(c =>
                {
                    c.Name(columnName);
                    if (!string.IsNullOrWhiteSpace(sqlType))
                    {
                        c.SqlType(sqlType);
                    }
                });
            };

            mapper.IsPersistentId((mi, d) =>
            {
                var isId = mi.Name.Equals("Id", StringComparison.InvariantCultureIgnoreCase);
                return(isId);
            });
            mapper.BeforeMapClass += (modelInspector, type, classCustomizer) =>
            {
                var tableName = MappingHelper.GetTableName(type);

                classCustomizer.Table(tableName);

                var imMutable = type.HasAttribute <ImMutableAttribute>(true);
                if (imMutable)
                {
                    classCustomizer.Mutable(false);
                }

                if (MappingHelper.IsEntity(type))
                {
                    try
                    {
                        var idProp = type.GetProperty("Id");
                        if (idProp != null)
                        // note: Id may be missing when entity has hand-written mapping but isn't derived from EntityWithTypedId<> (for example: NhIdentityUserLogin)
                        {
                            if (tableName.StartsWith("Abp") && (idProp.PropertyType == typeof(Int64) || idProp.PropertyType == typeof(int)))
                            {
                                // temporary map `Abp` tables without hilo
                                classCustomizer.Id(p =>
                                {
                                    p.Column("Id");
                                    p.Generator(NHGens.Identity);
                                });
                            }
                            else
                            {
                                var idColumn = idProp.GetAttribute <ColumnAttribute>()?.Name ?? "Id";

                                // get Id mapper
                                var idMapper = _idMapper.Invoke(idProp.PropertyType);
                                if (idMapper != null)
                                {
                                    classCustomizer.Id(p =>
                                    {
                                        idMapper.Invoke(p);
                                        p.Column(idColumn);
                                    });
                                }
                            }
                        }
                        else
                        {
                        }
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }

                var discriminatorColumn = MappingHelper.GetDiscriminatorColumn(type);
                if (!string.IsNullOrWhiteSpace(discriminatorColumn))
                {
                    classCustomizer.Discriminator(d =>
                    {
                        d.Column(discriminatorColumn);

                        if (MappingHelper.GetFilterUnknownDiscriminatorsFlag(type))
                        {
                            d.Force(true);
                        }
                    });

                    var discriminatorValue = MappingHelper.GetDiscriminatorValue(type);

                    classCustomizer.DiscriminatorValue(discriminatorValue);
                }

                // IMayHaveTenant support
                if (typeof(IMayHaveTenant).IsAssignableFrom(type))
                {
                    classCustomizer.Filter("MayHaveTenant", m =>
                    {
                    });
                }

                // ISoftDelete support
                if (typeof(ISoftDelete).IsAssignableFrom(type))
                {
                    classCustomizer.Filter("SoftDelete", m =>
                    {
                    });
                }
            };

            mapper.BeforeMapManyToOne += (modelInspector, propertyPath, map) =>
            {
                string columnPrefix = MappingHelper.GetColumnPrefix(propertyPath.LocalMember.DeclaringType);

                var lazyAttribute = propertyPath.LocalMember.GetAttribute <LazyAttribute>(true);
                var lazyRelation  = lazyAttribute != null?lazyAttribute.GetLazyRelation() : _defaultLazyRelation;

                if (lazyRelation != null)
                {
                    map.Lazy(lazyRelation);
                }

                var foreignKeyAttribute = propertyPath.LocalMember.GetAttribute <ForeignKeyAttribute>(true);
                var foreignKeyColumn    = foreignKeyAttribute != null
                    ? foreignKeyAttribute.Name
                    : columnPrefix + propertyPath.LocalMember.Name + "Id";

                //map.NotFound(NotFoundMode.Ignore); disabled due to performance issues, this option breaks lazy loading
                map.Column(foreignKeyColumn);

                var directlyMappedFk = propertyPath.LocalMember.DeclaringType?.GetProperty(foreignKeyColumn);

                if (foreignKeyColumn.ToLower() == "id" || directlyMappedFk != null)
                {
                    map.Insert(false);
                    map.Update(false);
                }

                var cascadeAttribute = propertyPath.LocalMember.GetAttribute <CascadeAttribute>(true);
                map.Cascade(cascadeAttribute?.Cascade ?? Cascade.Persist);
                map.Class(propertyPath.LocalMember.GetPropertyOrFieldType());
            };

            mapper.BeforeMapBag += (modelInspector, propertyPath, map) => {
                var inversePropertyAttribute = propertyPath.LocalMember.GetAttribute <InversePropertyAttribute>(true);
                if (inversePropertyAttribute != null)
                {
                    map.Key(keyMapper => keyMapper.Column(inversePropertyAttribute.Property));
                }
                else
                {
                    map.Key(keyMapper => keyMapper.Column(propertyPath.GetContainerEntity(modelInspector).Name + "Id"));
                }

                map.Cascade(Cascade.All);
                map.Lazy(CollectionLazy.Lazy);

                var bagMapper = map as NMIMPL.BagMapper;

                var manyToManyAttribute = propertyPath.LocalMember.GetAttribute <ManyToManyAttribute>(true);

                if (manyToManyAttribute != null)
                {
                    map.Cascade(Cascade.None);

                    if (!string.IsNullOrEmpty(manyToManyAttribute.Table))
                    {
                        map.Table(manyToManyAttribute.Table);
                    }

                    if (!string.IsNullOrEmpty(manyToManyAttribute.KeyColumn))
                    {
                        map.Key(keyMapper => keyMapper.Column(manyToManyAttribute.KeyColumn));
                    }
                    if (!string.IsNullOrEmpty(manyToManyAttribute.Where))
                    {
                        map.Where(manyToManyAttribute.Where);
                    }
                    if (!string.IsNullOrEmpty(manyToManyAttribute.OrderBy))
                    {
                        map.OrderBy(manyToManyAttribute.OrderBy);
                    }
                }
                else
                {
                    if (bagMapper != null && typeof(ISoftDelete).IsAssignableFrom(bagMapper.ElementType))
                    {
                        //TODO: Check IsDeletedColumn for Many-To-Many
                        map.Where($"{SheshaDatabaseConsts.IsDeletedColumn} = 0");
                    }
                }
            };

            mapper.BeforeMapManyToMany += (modelInspector, propertyPath, map) => {
                //map.NotFound(NotFoundMode.Ignore); disabled due to performance issues, this option breaks lazy loading

                var manyToManyAttribute = propertyPath.LocalMember.GetAttribute <ManyToManyAttribute>(true);
                if (manyToManyAttribute != null)
                {
                    if (!string.IsNullOrEmpty(manyToManyAttribute.ChildColumn))
                    {
                        map.Column(manyToManyAttribute.ChildColumn);
                    }
                }
            };

            foreach (var assembly in _assemblies)
            {
                var allTypes = !assembly.IsDynamic
                    ? assembly.GetExportedTypes()
                    : assembly.GetTypes();
                var allEntities = allTypes.Where(t => MappingHelper.IsEntity(t)).ToList();
                foreach (var entityType in allEntities)
                {
                    var classMapping = configuration.GetClassMapping(entityType);
                    if (classMapping == null)
                    {
                        _entitiesToMap.Add(entityType);
                    }
                }

                var mappingOverride = allTypes.Where(t => IsClassMapping(t) && !t.IsAbstract).ToList();
                foreach (var @override in mappingOverride)
                {
                    try
                    {
                        var entityType = GetEntityTypeByMapping(@override);

                        if (entityType.IsEntityType())
                        {
                            _defaultMapper.AddMapping(@override);
                            mapper.AddMapping(@override);

                            if (entityType != null && !entityType.IsAbstract && !_entitiesToMap.Contains(entityType))
                            {
                                _entitiesToMap.Add(entityType);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }
            }

            // sort entity types by hierarchy
            _entitiesToMap = MappingHelper.SortEntityTypesByInheritance(_entitiesToMap);

            /* for debug
             * foreach (var ent in _entitiesToMap)
             * {
             *  try
             *  {
             *      var mapping1 = mapper.CompileMappingFor(new List<Type> { ent });
             *  }
             *  catch (Exception e)
             *  {
             *      throw;
             *  }
             * }
             */

            HbmMapping mapping = mapper.CompileMappingFor(_entitiesToMap);

            configuration.AddDeserializedMapping(mapping, "AutoMapping");

            LastCompiledXml = mapping.AsString();
        }