public override Configuration Map(Configuration cfg)
        {
            ConventionModelMapper mapper = new ConventionModelMapper();

            mapper.IsEntity((x, y) => this.IsEntity(x, y, this.EntitiesAssemblyName));
            mapper.IsRootEntity((x, y) => this.IsRootEntity(x, y, this.EntitiesAssemblyName));
            mapper.IsOneToMany((x, y) => this.IsOneToMany(x, y));
            mapper.IsManyToOne((x, y) => this.IsManyToOne(x, y));
            mapper.IsManyToMany((x, y) => this.IsManyToMany(x, y));
            mapper.IsBag((x, y) => this.IsBag(x, y));
            mapper.IsSet((x, y) => this.IsSet(x, y));
            mapper.IsProperty((x, y) => this.IsProperty(x, y));
            mapper.IsPersistentProperty((x, y) => this.IsPersistentProperty(x, y));
            mapper.BeforeMapClass      += this.BeforeMapClass;
            mapper.BeforeMapProperty   += this.BeforeMapProperty;
            mapper.BeforeMapSet        += this.BeforeMapSet;
            mapper.BeforeMapOneToMany  += this.BeforeMapOneToMany;
            mapper.BeforeMapManyToOne  += this.BeforeMapManyToOne;
            mapper.BeforeMapManyToMany += BeforeMapManyToMany;

            HbmMapping mappings = mapper.CompileMappingFor(Assembly.Load(this.EntitiesAssemblyName).GetExportedTypes());

            cfg.AddMapping(mappings);

            return(cfg);
        }
示例#2
0
        public static void WithConventions(this ConventionModelMapper mapper, Configuration configuration)
        {
            Type baseEntityType = typeof(Entity);

            mapper.IsEntity((type, declared) => IsEntity(type));
            mapper.IsRootEntity((type, declared) => baseEntityType.Equals(type.BaseType));

            mapper.BeforeMapClass += (modelInspector, type, classCustomizer) => {
                classCustomizer.Id(c => c.Column("Id"));
                classCustomizer.Id(c => c.Generator(Generators.Identity));
                classCustomizer.Table(Inflector.Net.Inflector.Pluralize(type.Name.ToString()));
            };

            mapper.BeforeMapManyToOne += (modelInspector, propertyPath, map) => {
                map.Column(propertyPath.LocalMember.GetPropertyOrFieldType().Name + "Fk");
                map.Cascade(Cascade.Persist);
            };

            mapper.BeforeMapBag += (modelInspector, propertyPath, map) => {
                map.Key(keyMapper => keyMapper.Column(propertyPath.GetContainerEntity(modelInspector).Name + "Fk"));
                map.Cascade(Cascade.All);
            };

            AddConventionOverrides(mapper);

            HbmMapping mapping = mapper.CompileMappingFor(typeof(Customer).Assembly.GetExportedTypes().Where(t => IsEntity(t)));

            configuration.AddDeserializedMapping(mapping, "MyStoreMappings");
        }
示例#3
0
 private static void DefineBaseClass(ConventionModelMapper mapper, System.Type[] baseEntityToIgnore)
 {
     if (baseEntityToIgnore == null)
     {
         return;
     }
     mapper.IsEntity((type, declared) =>
                     baseEntityToIgnore.Any(x => x.IsAssignableFrom(type)) &&
                     !baseEntityToIgnore.Any(x => x == type) &&
                     !type.IsInterface);
     mapper.IsRootEntity((type, declared) => baseEntityToIgnore.Any(x => x == type.BaseType));
 }
示例#4
0
 private void DefineBaseClass(ConventionModelMapper mapper)
 {
     if (BaseEntityToIgnore == null)
     {
         return;
     }
     mapper.IsEntity((type, declared) =>
                     BaseEntityToIgnore.IsAssignableFrom(type) &&
                     BaseEntityToIgnore != type &&
                     !type.IsInterface);
     mapper.IsRootEntity((type, declared) => type.BaseType == BaseEntityToIgnore);
 }
示例#5
0
 private static void DefineBaseClass(ConventionModelMapper mapper)
 {
     if (BaseEntityToIgnore == null)
     {
         BaseEntityToIgnore = typeof(BaseDomainObject);
     }
     mapper.IsEntity((type, declared) =>
                     BaseEntityToIgnore.IsAssignableFrom(type) &&
                     BaseEntityToIgnore != type &&
                     !type.IsInterface);
     mapper.IsRootEntity((type, declared) => type.BaseType == BaseEntityToIgnore);
     //mapper.IsTablePerClassHierarchy((type, declared) =>true);
 }
示例#6
0
        protected override HbmMapping GetMappings()
        {
            var mapper = new ConventionModelMapper();

            System.Type baseEntityType = typeof(DomainObject);
            mapper.IsEntity((t, declared) => baseEntityType.IsAssignableFrom(t) && baseEntityType != t);
            mapper.IsRootEntity((t, declared) => baseEntityType == t.BaseType);
            mapper.Class <DomainObject>(r =>
            {
                r.Version(x => x.EntityVersion, map => { });
                r.Id(x => x.ID, map => map.Generator(Generators.Native));
            });
            mapper.Class <Class1>(r => r.IdBag(x => x.Class2List, map => map.Inverse(true), rel => rel.ManyToMany()));
            mapper.Class <Class2>(r => r.IdBag <Class1>("_class1List", map => map.Table("Class1List"), rel => rel.ManyToMany()));
            HbmMapping mappings = mapper.CompileMappingFor(new[] { typeof(Class1), typeof(Class2) });

            return(mappings);
        }
        public ISessionFactory Create()
        {
            var cfg = new Configuration();

            cfg.DataBaseIntegration(
                db =>
            {
                db.ConnectionString =
                    "Server=tcp:localhost;Database=DataSample;Trusted_Connection=true;Encrypt=False;";
                db.Dialect <MsSql2008Dialect>();
                db.BatchSize          = 250;
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                db.SchemaAction       = SchemaAutoAction.Update;
            }).SessionFactory().GenerateStatistics();

            var mapper = new ConventionModelMapper();

            // filter entities
            var baseEntityType = typeof(AbstractEntity);

            mapper.IsEntity(
                (t, declared) => baseEntityType.IsAssignableFrom(t) && baseEntityType != t && !t.IsInterface);
            mapper.IsRootEntity((t, declared) => baseEntityType.Equals(t.BaseType));

            // override base properties
            mapper.Class <AbstractEntity>(
                map =>
            {
                map.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
            });

            mapper.BeforeMapProperty += OnBeforeMapProperty;

            // compile
            var mapping =
                mapper.CompileMappingFor(
                    typeof(AbstractEntity).Assembly.GetExportedTypes().Where(type => typeof(AbstractEntity).IsAssignableFrom(type)));

            // use mappings
            cfg.AddMapping(mapping);

            // build
            return(cfg.BuildSessionFactory());
        }
示例#8
0
        public static HbmMapping CreateMappingConfiguration()
        {
            var mapper = new ConventionModelMapper();

            var baseEntityType = typeof(Entity);

            mapper.IsEntity((t, declared) => baseEntityType.IsAssignableFrom(t) && baseEntityType != t && !t.IsInterface);
            mapper.IsRootEntity((t, declared) => baseEntityType.Equals(t.BaseType));

            mapper.BeforeMapManyToOne += (insp, prop, map) => map.Column(prop.LocalMember.GetPropertyOrFieldType().Name + "Id");
            mapper.BeforeMapBag       += (insp, prop, map) => map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));
            mapper.BeforeMapBag       += (insp, prop, map) => map.Cascade(Cascade.All);

            mapper.Class <Album>(map => map.Id(x => x.AlbumId, m => m.Generator(Generators.Identity)));
            mapper.Class <Artist>(map => map.Id(x => x.ArtistId, m => m.Generator(Generators.Identity)));

            var mapping = mapper.CompileMappingFor(baseEntityType.Assembly.GetExportedTypes());

            return(mapping);
        }
        public WeatherDbConfig(IConfiguration appConfig, IOptions <NHibernateExportSettings> exportSettings)
        {
            this.DataBaseIntegration(db =>
            {
                db.Dialect <SQLiteDialect>();
                db.ConnectionString = appConfig.GetConnectionString("DefaultConnection");
            });
            ConfigurationExportSettings = exportSettings.Value;

            /*
             * // This chunk is for explicit coded mappings, uncomment WeatherForcastMapping to use this
             * var mapper = new ModelMapper();
             * //Here we're adding explicitly coded mappings but
             * //convention based mappings are supported
             * mapper.AddMappings(typeof(WeatherDbConfig).Assembly.GetExportedTypes());
             * var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
             *
             * AddMapping(mapping);
             */
            //http://fabiomaulo.blogspot.com/2011/04/nhibernate-32-mapping-by-code_13.html
            var mapper         = new ConventionModelMapper();
            var baseEntityType = typeof(EntityBase);

            mapper.IsEntity((t, declared) => baseEntityType.IsAssignableFrom(t) && baseEntityType != t && !t.IsInterface);
            mapper.IsRootEntity((t, declared) => baseEntityType.Equals(t.BaseType));

            mapper.Class <EntityBase>(map =>
            {
                map.Schema("weatherExample");
                map.Id(x => x.Id, idCfg => idCfg.Generator(Generators.Identity));
            });

            mapper.BeforeMapManyToOne += (insp, prop, map) => map.Column(prop.LocalMember.GetPropertyOrFieldType().Name + "Id");
            mapper.BeforeMapManyToOne += (insp, prop, map) => map.Cascade(Cascade.Persist);
            mapper.BeforeMapBag       += (insp, prop, map) => map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));
            mapper.BeforeMapBag       += (insp, prop, map) => map.Cascade(Cascade.All);


            ConfiguredMapping = mapper.CompileMappingFor(baseEntityType.Assembly.GetExportedTypes().Where(t => t.Namespace.EndsWith("Models")));
            AddMapping(ConfiguredMapping);
        }
        public void WhenPropertyVersionFromBaseEntityThenFindItAsVersion()
        {
            var mapper         = new ConventionModelMapper();
            var baseEntityType = typeof(BaseEntity);

            mapper.IsEntity((t, declared) => baseEntityType.IsAssignableFrom(t) && baseEntityType != t && !t.IsInterface);
            mapper.IsRootEntity((t, declared) => baseEntityType.Equals(t.BaseType));
            mapper.Class <BaseEntity>(
                map =>
            {
                map.Id(x => x.Id, idmap => { });
                map.Version(x => x.Version, vm => { });
            });
            var hbmMapping = mapper.CompileMappingFor(new[] { typeof(Person) });

            var hbmClass   = hbmMapping.RootClasses[0];
            var hbmVersion = hbmClass.Version;

            Assert.That(hbmVersion, Is.Not.Null);
            Assert.That(hbmVersion.name, Is.EqualTo("Version"));
        }
        public Configuration GetConfiguration()
        {
            if (_configuration != null)
            {
                return(_configuration);
            }

            Configuration cfg = new Configuration();

            cfg.DataBaseIntegration(db =>
            {
                db.ConnectionString = "Server=localhost;Integrated Security=SSPI;Database=nhibernatetestdb";
                db.Dialect <MsSql2012Dialect>();
                db.Driver <Sql2008ClientDriver>();
            });

            var mapper = new ConventionModelMapper();

            Type baseEntityType = typeof(BaseEntity);

            mapper.IsEntity((t, _) => baseEntityType.IsAssignableFrom(t) && baseEntityType != t && !t.IsInterface);
            mapper.IsRootEntity((t, _) => baseEntityType == t.BaseType);
            mapper.Class <BaseEntity>(t => t.Id(e => e.Id, m => m.Generator(new IdentityGeneratorDef())));
            mapper.BeforeMapManyToOne += (i, p, m) => m.Cascade(Cascade.Persist);
            mapper.BeforeMapList      += (i, p, m) => m.Cascade(Cascade.Persist);
            mapper.BeforeMapSet       += (i, p, m) => m.Cascade(Cascade.Persist);
            mapper.BeforeMapBag       += (i, p, m) => m.Cascade(Cascade.Persist);

            var mapping = mapper.CompileMappingFor(typeof(BaseEntity).Assembly.ExportedTypes.Where(t => typeof(BaseEntity).IsAssignableFrom(t)));

            cfg.AddMapping(mapping);

            _configuration = cfg;

            var updateSchema = new SchemaUpdate(_configuration);

            updateSchema.Execute(false, true);

            return(_configuration);
        }
        public void WhenVersionFromBaseEntityThenShouldntMapVersionAsProperty()
        {
            var mapper         = new ConventionModelMapper();
            var baseEntityType = typeof(BaseEntity);

            mapper.IsEntity((t, declared) => baseEntityType.IsAssignableFrom(t) && baseEntityType != t && !t.IsInterface);
            mapper.IsRootEntity((t, declared) => baseEntityType == t.BaseType);
            mapper.Class <BaseEntity>(
                map =>
            {
                map.Id(x => x.Id, idmap => { });
                map.Version(x => x.Version, vm => { });
            });
            var hbmMapping = mapper.CompileMappingFor(new[] { typeof(Person) });

            var hbmClass   = hbmMapping.RootClasses[0];
            var hbmVersion = hbmClass.Version;

            Assert.That(hbmVersion, Is.Not.Null);
            Assert.That(hbmVersion.name, Is.EqualTo("Version"));
            Assert.That(hbmClass.Properties, Is.Empty, "because one is the POID and the other is the version");
        }
示例#13
0
        public void Configure(Configuration configuration)
        {
            var mapper = new ConventionModelMapper();

            var baseEntityType = typeof(Entity);

            mapper.IsEntity((t, declared) => baseEntityType.IsAssignableFrom(t) && baseEntityType != t && !t.IsInterface);
            mapper.IsRootEntity((t, declared) => baseEntityType.Equals(t.BaseType));

            mapper.BeforeMapManyToOne += (insp, prop, map) => map.Column(prop.LocalMember.GetPropertyOrFieldType().Name + "Id");
            mapper.BeforeMapBag       += (insp, prop, map) => map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));
            mapper.BeforeMapBag       += (insp, prop, map) => map.Cascade(Cascade.All);

            mapper.Class <Entity>(map =>
            {
                map.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
                map.Version(x => x.Version, m => m.Generated(VersionGeneration.Never));
            });

            var mapping = mapper.CompileMappingFor(baseEntityType.Assembly.GetExportedTypes());

            configuration.AddDeserializedMapping(mapping, "Cronos");
        }
示例#14
0
        public static HbmMapping Generate()
        {
            //Conventions
            var mapper     = new ConventionModelMapper();
            var baseEntity = typeof(EntityBase);

            mapper.BeforeMapProperty += (ispector, member, customizer) => customizer.Length(40);

            mapper.BeforeMapManyToOne +=
                (insp, prop, map) => map.Column(prop.LocalMember.GetPropertyOrFieldType().Name + "Id");

            mapper.BeforeMapManyToOne +=
                (insp, prop, map) => map.Cascade(Cascade.Persist);

            mapper.BeforeMapBag +=
                (insp, prop, map) => map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));

            mapper.BeforeMapSet +=
                (insp, prop, map) => map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));

            mapper.IsEntity((t, d) => baseEntity.IsAssignableFrom(t) && baseEntity != t);

            mapper.IsRootEntity((t, d) => t.BaseType == baseEntity);

            mapper.IsSet(IsSetFieldType);

            Customize(mapper);

            HbmMapping mappings = mapper.CompileMappingFor(new[]
            {
                typeof(Customization), typeof(Order),
                typeof(Payment),
                typeof(OrderItem), typeof(Product)
            });

            return(mappings);
        }
示例#15
0
        public static void WithConventions(this ConventionModelMapper mapper)
        {
            var baseEntityType = typeof(Entity);

            mapper.IsEntity((type, declared) => baseEntityType.IsAssignableFrom(type) && baseEntityType != type && !type.IsInterface);
            mapper.IsRootEntity((type, declared) => baseEntityType.Equals(type.BaseType));

            mapper.BeforeMapManyToOne += (modelInspector, propertyPath, map) => map.Column(propertyPath.LocalMember.GetPropertyOrFieldType().Name + "Id");
            //mapper.BeforeMapManyToOne += (modelInspector, propertyPath, map) => map.Cascade(Cascade.Persist);
            mapper.BeforeMapBag += (modelInspector, propertyPath, map) => map.Key(keyMapper => keyMapper.Column(propertyPath.GetContainerEntity(modelInspector).Name + "Id"));
            //mapper.BeforeMapBag += (modelInspector, propertyPath, map) => map.Cascade(Cascade.All);

            mapper.BeforeMapClass += (modelInspector, type, classCustomizer) =>
            {
                classCustomizer.Id(c => c.Column(type.Name + "Id"));
                classCustomizer.Id(c => c.Generator(Generators.GuidComb));
                classCustomizer.Table(ReservedTableNameHandler(type));
            };

            mapper.Class <Entity>(map => {
                map.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
                map.Version(x => x.Version, m => m.Generated(VersionGeneration.Always));
            });
        }
示例#16
0
        public void ApplyTo(ConventionModelMapper modelMapper)
        {
            modelMapper.BeforeMapClass += (inspector, type, customizer) =>
            {
                customizer.Table($"`{type.Name}`");

                customizer.Id(mapper =>
                {
                    mapper.Generator(Generators.Identity);
                    mapper.Access(Accessor.Field);
                });

                customizer.Version(type.GetProperty(nameof(Entity.Version)), mapper => { });
            };

            modelMapper.BeforeMapManyToOne += (inspector, member, customizer) =>
            {
                customizer.Column(mapper => mapper.Name(member.ToColumnName() + "Id"));
                customizer.ForeignKey(
                    $"FK_{member.GetContainerEntity(inspector).Name.ToUpper()}_{member.LocalMember.Name.ToUpper()}");
                customizer.Index(
                    ($"IDX_{member.GetContainerEntity(inspector).Name.ToUpper()}_{member.LocalMember.Name.ToUpper()}"));

                if (member.LocalMember.GetPropertyOrFieldType().IsSubclassOf(typeof(AggregateRoot)) == false)
                {
                    customizer.Cascade(Cascade.Persist);
                }

                var uniqueAttribute = member.LocalMember.GetCustomAttribute <UniqueAttribute>();
                if (uniqueAttribute != null)
                {
                    if (string.IsNullOrEmpty(uniqueAttribute.Key) == false)
                    {
                        customizer.UniqueKey($"UQ_{uniqueAttribute.Key}");
                    }
                    else
                    {
                        customizer.Unique(true);
                    }
                }
            };

            modelMapper.BeforeMapManyToMany += (inspector, member, customizer) =>
            {
                customizer.Column(mapper => mapper.Name(member.ToColumnName().TrimEnd('s') + "Id"));
                customizer.ForeignKey(
                    $"FK_{member.GetContainerEntity(inspector).Name.ToUpper()}_{member.LocalMember.Name.ToUpper()}_{member.ToColumnName().TrimEnd('s') + "Id"}");
            };

            modelMapper.BeforeMapProperty += (inspector, member, customizer) =>
            {
                var memberType      = member.LocalMember.GetPropertyOrFieldType();
                var uniqueAttribute = member.LocalMember.GetCustomAttribute <UniqueAttribute>();
                if (uniqueAttribute != null)
                {
                    if (string.IsNullOrEmpty(uniqueAttribute.Key) == false)
                    {
                        customizer.UniqueKey($"UQ_{uniqueAttribute.Key}");
                    }
                    else
                    {
                        customizer.Unique(true);
                    }
                }

                var indexAttribute = member.LocalMember.GetCustomAttribute <IndexAttribute>();
                if (indexAttribute != null)
                {
                    customizer.Index(
                        $"IDX_{member.GetContainerEntity(inspector).Name.ToUpper()}_{member.ToColumnName().ToUpper()}");
                }

                if (this.userTypes.TryGetValue(memberType, out var userType))
                {
                    customizer.Type(userType, null);
                }

                if (memberType == typeof(byte[]))
                {
                    customizer.Length(int.MaxValue);
                }
            };

            modelMapper.BeforeMapJoinedSubclass += (inspector, type, customizer) =>
            {
                customizer.Key(mapper => mapper.Column(columnMapper => columnMapper.Name($"{type.BaseType.Name}Id")));
                customizer.Key(mapper => mapper.ForeignKey($"FK_{type.Name.ToUpper()}_{type.BaseType.Name.ToUpper()}"));
            };

            modelMapper.BeforeMapBag  += OnBeforeMapCollection;
            modelMapper.BeforeMapList += OnBeforeMapCollection;
            modelMapper.BeforeMapList += (inspector, member, customizer) =>
            {
                customizer.Inverse(false);
                customizer.Index(m => m.Column("`Index`"));
            };
            modelMapper.BeforeMapSet   += OnBeforeMapCollection;
            modelMapper.BeforeMapIdBag += OnBeforeMapCollection;

            modelMapper.BeforeMapElement += (inspector, member, customizer) => { customizer.Column("Value"); };

            modelMapper.IsEntity((type, b) => typeof(Entity).IsAssignableFrom(type) && type != typeof(AggregateRoot));
            modelMapper.IsRootEntity((type, b) =>
                                     type.BaseType == typeof(Entity) || type.BaseType == typeof(AggregateRoot));
            modelMapper.IsVersion((property, b) => property.Name == nameof(Entity.Version));
            modelMapper.IsProperty((info, declared) => declared || this.userTypes.ContainsKey(info.GetPropertyOrFieldType()));
            modelMapper.IsOneToMany((memberInfo, declared) =>
            {
                if (declared)
                {
                    return(true);
                }

                var collectionType = memberInfo.GetPropertyOrFieldType();

                return(collectionType.IsEnumerableOf <Entity>() &&
                       collectionType.IsEnumerableOf <AggregateRoot>() == false);
            });

            modelMapper.IsManyToMany((memberInfo, declared) =>
                                     declared || memberInfo.GetPropertyOrFieldType().IsEnumerableOf <AggregateRoot>());
            modelMapper.IsList((info, declared) =>
            {
                if (declared)
                {
                    return(true);
                }

                var backingField = info.DeclaringType.GetField(info.Name,
                                                               BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase);

                var propertyType  = backingField?.GetPropertyOrFieldType() ?? info.GetPropertyOrFieldType();
                var isGenericList = propertyType.IsGenericType &&
                                    propertyType.GetGenericTypeDefinition() == typeof(IList <>);
                return(isGenericList);
            });
        }
示例#17
0
        public static HbmMapping GetIdentityMappings(List <Type> entities)
        {
            var mapper = new ConventionModelMapper();

            // 1. Antes de mapear as propriedades, verificar atributos;
            mapper.BeforeMapProperty += (insp, prop, map) =>
            {
                var stringLength = prop.LocalMember.GetAttribute <StringLengthAttribute>();
                if (stringLength != null)
                {
                    map.Length(stringLength.MaximumLength);
                }

                var required = prop.LocalMember.GetAttribute <RequiredAttribute>();
                if (required != null)
                {
                    map.NotNullable(true);
                }

                var name = prop.LocalMember.GetAttribute <ColumnAttribute>();
                if (name != null)
                {
                    map.Column(name.Name);
                }
            };

            // 2. Antes de mapear as many-to-one e one-to-many, verificar Ids;
            mapper.BeforeMapManyToOne += (insp, prop, map) =>
            {
                map.Column(prop.LocalMember.GetPropertyOrFieldType().Name + "Id");
                map.Cascade(Cascade.Persist);
            };

            mapper.BeforeMapBag += (insp, prop, map) =>
            {
                map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));
                map.Cascade(Cascade.All.Include(Cascade.DeleteOrphans));
                map.BatchSize(10);
            };

            // 3. Match
            Func <Type, bool, bool> matchRootEntity =
                (type, wasDeclared) => typeof(EntityWithTypedId <int>).Equals(type.BaseType) ||
                typeof(EntityWithTypedId <string>).Equals(type.BaseType);

            mapper.IsEntity((type, wasDeclared) => entities.Contains(type));
            mapper.IsRootEntity(matchRootEntity);
            mapper.IsComponent((type, declared) => entities.Contains(type));

            mapper.MapAllEnumsToStrings();

            List <Type> mappings =
                Assembly.GetAssembly(typeof(AlunoMap))
                .GetExportedTypes()
                .Where(t => t.BaseType.IsGenericType &&
                       (t.BaseType.GetGenericTypeDefinition().Equals(typeof(ClassMapping <>)) ||
                        t.BaseType.GetGenericTypeDefinition().Equals(typeof(SubclassMapping <>)) ||
                        t.BaseType.GetGenericTypeDefinition().Equals(typeof(JoinedSubclassMapping <>)) ||
                        t.BaseType.GetGenericTypeDefinition().Equals(typeof(UnionSubclassMapping <>))))
                .ToList();

            mapper.AddMappings(mappings);

            return(mapper.CompileMappingFor(entities));
        }
        private Configuration ConfigureNHibernate()
        {
            var config = new Configuration();

            config.DataBaseIntegration(
                db =>
                    {
                        db.Dialect<SQLiteDialect>();
                        db.Driver<SQLite20Driver>();
                        db.SchemaAction = SchemaAutoAction.Recreate;
                        db.ConnectionString = "Data Source=:memory:;Version=3;New=True;";
                    }).SetProperty(Environment.CurrentSessionContextClass, "thread_static");

            var mapper = new ConventionModelMapper();

            // filter entities
            var baseEntityType = typeof(AbstractEntity);
            mapper.IsEntity(
                (t, declared) => baseEntityType.IsAssignableFrom(t) && baseEntityType != t && !t.IsInterface);
            mapper.IsRootEntity((t, declared) => baseEntityType == t.BaseType);

            // override base properties
            mapper.Class<AbstractEntity>(map => map.Id(x => x.Id, m => m.Generator(Generators.GuidComb)));

            mapper.BeforeMapProperty += (modelinspector, member, propertycustomizer) =>
                                            {
                                                if (member.LocalMember.Name == "Name")
                                                {
                                                    propertycustomizer.Unique(true);
                                                }
                                            };

            // compile
            var mapping =
                mapper.CompileMappingFor(
                    typeof(Person).Assembly.GetExportedTypes().Where(
                        type => typeof(AbstractEntity).IsAssignableFrom(type)));

            // use mappings
            config.AddMapping(mapping);

            return config;
        }
示例#19
0
        public void Configure(Configuration configuration, Type[] types)
        {
            var assemblies = types.Select(x => x.Assembly).Distinct().ToArray();

            var mapper = new ConventionModelMapper();

            var baseEntityType  = typeof(IGenericEntity);
            var baseEntityTypes = new[]
            {
                typeof(IEntity),
                typeof(Entity),
                typeof(AuditableEntity)
            };

            mapper.IsEntity((t, declared) =>
            {
                var isEntity = baseEntityType.IsAssignableFrom(t) &&
                               !baseEntityTypes.Contains(t) &&
                               !t.ContainsGenericParameters &&
                               !t.IsInterface;
                //if (isEntity)
                //{
                //    Logger.Debug("IsEntity --> {0} {1}", declared, t.FullName);
                //}
                return(isEntity);
            });
            mapper.IsRootEntity((t, declared) =>
            {
                var isRootEntity = baseEntityTypes.Contains(t.BaseType) && !baseEntityTypes.Contains(t);
                //if (isRootEntity)
                //{
                //    Logger.Debug("IsRootEntity --> {0} {1}", declared, t.FullName);
                //}
                return(isRootEntity);
            });

            mapper.BeforeMapProperty += (insp, prop, map) =>
            {
                var type = prop.LocalMember.GetPropertyOrFieldType();
                if (type.IsEnum)
                {
                    var userType = typeof(EnumStringType <>).MakeGenericType(type);
                    map.Type((IType)Activator.CreateInstance(userType));
                }
            };

            mapper.BeforeMapManyToOne += (insp, prop, map) =>
            {
                map.Column(prop.LocalMember.Name + "Id");
                map.Cascade(Cascade.Persist);
                map.ForeignKey("FK_" + prop.GetContainerEntity(insp).Name + "_" + prop.LocalMember.Name);
                map.Index("IX_" + prop.GetContainerEntity(insp).Name + "_" + prop.LocalMember.Name);
            };
            mapper.BeforeMapList += (insp, prop, map) =>
            {
                map.Cascade(Cascade.All);
                map.Table(prop.GetContainerEntity(insp).Name + "_" + prop.LocalMember.Name);
                map.Index(m => m.Column("Idx"));
                map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));
            };
            mapper.BeforeMapBag += (insp, prop, map) =>
            {
                map.Cascade(Cascade.All);
                map.Table(prop.GetContainerEntity(insp).Name + "_" + prop.LocalMember.Name);
                map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));
            };
            mapper.BeforeMapSet += (insp, prop, map) =>
            {
                map.Cascade(Cascade.All);
                map.Table(prop.GetContainerEntity(insp).Name + "_" + prop.LocalMember.Name);
                map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));
            };
            mapper.BeforeMapMap += (insp, prop, map) =>
            {
                map.Cascade(Cascade.All);
                map.Table(prop.GetContainerEntity(insp).Name + "_" + prop.LocalMember.Name);
                map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));
            };
            mapper.BeforeMapIdBag += (insp, prop, map) =>
            {
                map.Cascade(Cascade.All);
                map.Table(prop.GetContainerEntity(insp).Name + "_" + prop.LocalMember.Name);
                map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));
                map.Id(m => m.Column("Id"));
            };

            mapper.Class <Entity>(
                map =>
            {
                map.DynamicUpdate(true);
                map.DynamicInsert(true);
                map.Id(x => x.Id,
                       m => m.Generator(Generators.HighLow,
                                        h => h.Params(new
                {
                    max_lo = MaxLo
                }))
                       );
                map.Version(x => x.Version, m => m.Generated(VersionGeneration.Never));
            });

            CustomizeMappings(mapper);

            // customizations start

            var customizedMappings = assemblies
                                     .SelectMany(x => x.GetExportedTypes())
                                     .Where(x => !x.IsAbstract)
                                     .Where(t => IsGenericSubclassOf(t, typeof(ClassMapping <>)) ||
                                            IsGenericSubclassOf(t, typeof(SubclassMapping <>)) ||
                                            IsGenericSubclassOf(t, typeof(JoinedSubclassMapping <>)) ||
                                            IsGenericSubclassOf(t, typeof(UnionSubclassMapping <>)))
                                     .ToArray();

            //Logger.Debug("Applying mapping customizations: " + string.Join(", ", customizedMappings.Select(x => x.Name).OrderBy(x => x)));
            mapper.AddMappings(customizedMappings);

            // customizations end

            //Logger.Debug("Compiling mappings for types: " + string.Join(", ", types.Select(x => x.Name).OrderBy(x => x)));
            HbmMapping mapping;

            try
            {
                mapping = mapper.CompileMappingFor(types);
            }
            catch (NotSupportedException ex)
            {
                throw new NotSupportedException(
                          "This exception happened in the past when forgot to map a new property as JSON-serialized and its type is not supported by NH",
                          ex);
            }

            var mappingFixers = assemblies
                                .SelectMany(x => x.GetExportedTypes())
                                .Where(x => !x.IsAbstract)
                                .Where(t => typeof(IMappingFixer).IsAssignableFrom(t))
                                .ToArray();

            foreach (var mappingFixer in mappingFixers)
            {
                var fixer = (IMappingFixer)Activator.CreateInstance(mappingFixer);
                fixer.Fix(mapping);
            }

            try
            {
                File.WriteAllText("core.hbm.xml", mapping.AsString());
            }
            catch (Exception)
            {
                // this is just for development/debugging info...
                // when deployed, most probably there will not be
                // permissions to write anything, so just ignore errors here
            }

            configuration.AddDeserializedMapping(mapping, null);
        }
示例#20
0
        /// <summary>
        ///   Creates and initializes the model mapper.
        /// </summary>
        /// <returns> The model mapper. </returns>
        protected virtual ModelMapper CreateModelMapper()
        {
            var mapper = new ConventionModelMapper();

            mapper.BeforeMapClass += (inspector, type, customizer) =>
            {
                customizer.Table(NamingConvention.Table(inspector, type));

                PropertyPath property = inspector.FindPersistentId(type);

                if (property != null)
                {
                    customizer.Id(property.LocalMember, map =>
                    {
                        map.Column(
                            NamingConvention.Column
                                (inspector,
                                property));

                        ApplyIdConventions(map,
                                           property
                                           .
                                           LocalMember
                                           as
                                           PropertyInfo);
                    });
                }
            };

            mapper.BeforeMapJoinedSubclass += (inspector, type, customizer) =>
            {
                var id = inspector.FindPersistentId(type.BaseType);


                customizer.Table(NamingConvention.Table(inspector, type));
                customizer.Key(
                    key =>
                {
                    key.Column(NamingConvention.KeyColumn(inspector, id,
                                                          type.BaseType));
                    key.ForeignKey(NamingConvention.ForeignKey(inspector, id, type, type.BaseType));
                });
            };

            mapper.BeforeMapProperty += (inspector, member, customizer) =>
            {
                if (!inspector.IsPersistentId(member.LocalMember) &&
                    !inspector.IsPersistentProperty(member.LocalMember))
                {
                    return;
                }

                customizer.Column(NamingConvention.Column(inspector, member));

                Type type = member.LocalMember.GetPropertyOrFieldType();

                ApplyPropertyConventions(customizer, member, type, GetMemberAttributes(member.LocalMember));
            };

            mapper.BeforeMapManyToOne += (inspector, member, customizer) =>
            {
                customizer.Column(NamingConvention.Column(inspector, member));
                customizer.ForeignKey(NamingConvention
                                      .ForeignKey(inspector, member));
                customizer.Index(NamingConvention.Index(inspector, member));

                Type type = member.LocalMember.GetPropertyOrFieldType();

                ApplyManyToOneConventions(customizer, member, type, GetMemberAttributes(member.LocalMember));
            };

            mapper.BeforeMapBag += (inspector, member, customizer) =>
            {
                var inverse = GetLikelyInverseProperty(member);

                var keyColumn = inverse == null
                                                               ? NamingConvention.KeyColumn(inspector, member)
                                                               : NamingConvention.Column(inspector, inverse);


                customizer.Key(key => key.Column(keyColumn));

                ApplyBagConventions(customizer, member);
            };

            mapper.BeforeMapSet += (inspector, member, customizer) =>
            {
                var inverse = GetLikelyInverseProperty(member);

                var keyColumn = inverse == null
                                                               ? NamingConvention.KeyColumn(inspector, member)
                                                               : NamingConvention.Column(inspector, inverse);

                customizer.Key(key => key.Column(keyColumn));

                ApplySetConventions(customizer, member);
            };

            mapper.BeforeMapList += (inspector, member, customizer) =>
            {
                var inverse = GetLikelyInverseProperty(member);

                var keyColumn = inverse == null
                                                                ? NamingConvention.KeyColumn(inspector, member)
                                                                : NamingConvention.Column(inspector, inverse);

                customizer.Key(key => key.Column(keyColumn));
                customizer.Index(index => index.Column(NamingConvention.IndexColumn(inspector, member)));

                ApplyListConventions(customizer, member);
            };

            mapper.BeforeMapMap += (inspector, member, customizer) =>
            {
                var inverse = GetLikelyInverseProperty(member);

                var keyColumn = inverse == null
                                                               ? NamingConvention.KeyColumn(inspector, member)
                                                               : NamingConvention.Column(inspector, inverse);

                // TODO: figure out how to set the map key column (not just the foreign key)

                customizer.Key(key => key.Column(keyColumn));

                ApplyMapConventions(customizer, member);
            };


            mapper.IsEntity(IsEntity);
            mapper.IsRootEntity(IsRootEntity);
            //mapper.IsTablePerClassHierarchy(IsTablePerClassHierarchy);

            return(mapper);
        }
示例#21
0
 public void ApplyMapping(ConventionModelMapper mapper)
 {
     mapper.IsRootEntity(IsRootEntity);
 }
示例#22
0
        private static HbmMapping ImplicitMapping()
        {
            var mapper = new ConventionModelMapper();

            mapper.IsEntity((t, d) => IsEntity(t));
            mapper.IsRootEntity((t, declared) => IsEntity(t) && !IsEntity(t.BaseType));
            mapper.IsComponent((t, d) => d);
            mapper.IsBag((mi, d) => d);

            mapper.IsPersistentProperty((mi, d) =>
            {
                if (mi.MemberType != MemberTypes.Property)
                {
                    return(false);
                }
                var pi = (PropertyInfo)mi;
                return(pi.CanRead && pi.CanWrite);
            });

            mapper.BeforeMapProperty += (model, member, prop) =>
            {
                var type = member.LocalMember.GetPropertyOrFieldType();
                if (type == typeof(DateTime))
                {
                    prop.Type <UtcDateTimeType>();
                }
                else if (type == typeof(JObject))
                {
                    prop.Type <JObjectType>();
                    prop.Length(65536); // medium clob
                }
            };

            mapper.BeforeMapSet += (model, member, set) =>
            {
                set.Key(k => k.Column(member.GetContainerEntity(model).Name + "Id"));
                set.Cascade(Cascade.All | Cascade.DeleteOrphans);
            };

            mapper.BeforeMapManyToOne += (model, member, mto) =>
            {
                mto.Column(member.LocalMember.Name + "Id");
            };

            mapper.BeforeMapClass += (model, type, cls) =>
            {
                cls.Id(id =>
                {
                    id.Column("Id");
                    id.Generator(Generators.HighLow, g => g.Params(new { max_lo = 100 }));
                });
                cls.Table(type.Name);
                cls.Lazy(false);
            };

            // add conformist mappings
            mapper.AddMappings(Assembly.GetAssembly(typeof(PersistentAttribute)).GetExportedTypes());

            // apply above conventions
            return(mapper.CompileMappingFor(typeof(PersistentAttribute).Assembly.GetExportedTypes().Where(IsEntity)));
        }