예제 #1
0
        public Configuration GetConfiguration()
        {
            var NHibernateAssembly = Assembly.Load("Naftan.Maintenance.NHibernate");
            var DomainAssembly     = Assembly.Load("Naftan.Maintenance.Domain");
            var CommonAssembly     = Assembly.Load("Naftan.Common");

            var msSqlDatabase = MsSqlConfiguration.MsSql2008
                                .UseOuterJoin()
                                .ConnectionString(s => s.FromConnectionStringWithKey("maintenance"))
                                .UseReflectionOptimizer()
                                .AdoNetBatchSize(100);

            var automapping = AutoMap.Assemblies(new AutomappingConfig(), CommonAssembly, DomainAssembly)
                              .Conventions.AddAssembly(CommonAssembly)
                              .AddMappingsFromAssembly(NHibernateAssembly)
                              .UseOverridesFromAssembly(NHibernateAssembly);

            FluentConfiguration cfg = Fluently.Configure()
                                      .Database(msSqlDatabase)
                                      .Mappings(x => x.AutoMappings.Add(automapping)
                                                );

            var configuration = cfg.BuildConfiguration();

            return(configuration);
        }
예제 #2
0
        public Configuration BuildConfiguration(string connectionString, bool debug = false)
        {
            var configuration = new Configuration();

            var builder = Fluently
                          .Configure(configuration)
                          .ProxyFactoryFactory <DefaultProxyFactoryFactory>()
                          .Database(MsSqlConfiguration.MsSql2012.ConnectionString(connectionString)
                                    .ShowSql()
                                    .FormatSql()
                                    .Dialect <MsSql2012Dialect>()
                                    )
                          .ExposeConfiguration(c => { c.SetProperty("hbm2ddl.keywords", "auto-quote"); })
                          .Mappings(m =>
            {
                var model = AutoMap.Assemblies(new AppAutomappingCfg(), _assemblies);
                foreach (var assembly in _assemblies)
                {
                    model
                    .UseOverridesFromAssembly(assembly)
                    .Conventions
                    .AddAssembly(assembly);
                }
                m.AutoMappings.Add(model);
            })
            ;

            _config = builder
                      .BuildConfiguration();

            return(_config);
        }
예제 #3
0
        public NHibernate.Cfg.Configuration BuildConfiguration(string connectionString, bool debug = false)
        {
            var configuration = new NHibernate.Cfg.Configuration();

            configuration.SetProperty(Environment.ShowSql, "false");
            //configure NH to use ISet from .NET instead of from Iesi.Collections
            //configuration.SetProperty(Environment.CollectionTypeFactoryClass, typeof (Net4CollectionTypeFactory).AssemblyQualifiedName);

            var builder = Fluently
                          .Configure(configuration)
                          .ProxyFactoryFactory <DefaultProxyFactoryFactory>()
                          .Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString)
                                    //.ShowSql()
                                    //.FormatSql()
                                    .Dialect <MsSql2008Dialect>()
                                    )
                          .ExposeConfiguration(c =>
            {
                c.SetProperty(Environment.BatchSize, BatchSize.ToString(CultureInfo.InvariantCulture));
                c.SetProperty("hbm2ddl.keywords", "auto-quote");

                if (debug)
                {
                    c.SetProperty(Environment.ShowSql, "true");
                    c.SetProperty(Environment.FormatSql, "true");
                    c.SetProperty("LogSqlInConsole", "true");
                }
                else
                {
                    c.SetProperty(Environment.ShowSql, "false");
                    c.SetProperty(Environment.FormatSql, "false");
                    c.SetProperty("LogSqlInConsole", "false");
                }
                c.SetProperty("nhibernate-logger", typeof(NLogFactory).AssemblyQualifiedName);
            })
                          .Mappings(m =>
            {
                var model = AutoMap.Assemblies(new AppAutomappingCfg(), _assemblies);
                m.AutoMappings.Add(model);
            })
            ;

            if (debug)
            {
                builder = builder.ExposeConfiguration(cfg =>
                {
                    const string schemaPath = @"c:\temp\nh_mappings_export\schema.sql";
                    using (var file = File.Open(schemaPath, FileMode.CreateNew))
                        using (var writer = new StreamWriter(file))
                        {
                            var se = new SchemaExport(cfg);
                            se.Create(writer, false);
                        }
                });
            }
            _config = builder
                      .BuildConfiguration();

            return(_config);
        }
예제 #4
0
        public Configuration Generate()
        {
            var currentAssembly = Assembly.GetExecutingAssembly();
            var assemblies      = _assemblyLoader
                                  .GetAppDomainAssembly(_localStorageSettings.AssemblyFilter);
            var fluentConfig = Fluently.Configure()
                               .Database(_localStorageSettings.Dialect)
                               .Mappings(m =>
            {
                var autoMapping = AutoMap
                                  .Assemblies(
                    new ModelAutomappingConfiguration(),
                    assemblies
                    )
                                  .Conventions
                                  .AddAssembly(currentAssembly)
                                  .UseOverridesFromAssembly(currentAssembly);

                foreach (var assembly in assemblies)
                {
                    autoMapping.UseOverridesFromAssembly(assembly);
                }

                m.AutoMappings.Add(autoMapping);
            });

            return(fluentConfig.BuildConfiguration());
        }
        private AutoPersistenceModel GetAutoPersistenceModel()
        {
            var autoPersistenceModel = AutoMap.Assemblies(new AutomappingConfiguration(), _sessionContext.LocateDomainAssemblies().ToArray());

            // Add Pillar NHibernate conventions
            autoPersistenceModel = autoPersistenceModel.Conventions.AddFromAssemblyOf <AutomappingConfiguration>();

            // To allow two persistent classes with the same unqualified name


            // Add conventions and overrides from infrastructure assebmlies
            var infrastructureAssebmlies = _sessionContext.LocateInfrastructureAssemblies();

            foreach (var infrastructureAssebmly in infrastructureAssebmlies)
            {
                autoPersistenceModel = autoPersistenceModel
                                       .Conventions.AddAssembly(infrastructureAssebmly)
                                       .UseOverridesFromAssembly(infrastructureAssebmly);
            }
            foreach (var type in _sessionContext.IgnoreBaseTypes())
            {
                autoPersistenceModel.IgnoreBase(type);
            }
            autoPersistenceModel.AddFilter <AppFilterSoftDelete>();
            autoPersistenceModel.AddFilter <AppFilterOrganization>();
            return(autoPersistenceModel);
        }
예제 #6
0
        public static ISessionFactory Initilize()
        {
            var assembly     = Assembly.GetAssembly(typeof(Organization));
            var fluentConfig = Fluently.Configure()
                               .Database(SQLiteConfiguration.Standard.UsingFile("Data/Invoice.sqlite").ShowSql)
                               .Mappings(m =>
            {
                m.AutoMappings.Add(
                    AutoMap
                    .Assemblies(new MyAutomappingConfig(), assembly)
                    .Conventions.Add <CascadConvention>())
                ;
                m.FluentMappings.AddFromAssembly(assembly);
            })
                               .ExposeConfiguration(x => x.SetProperty("expiration", "900"))
            ;


            if (!Directory.Exists("Data"))
            {
                Directory.CreateDirectory("Data");
            }

            fluentConfig.ExposeConfiguration(x =>
                                             new SchemaExport(x).SetOutputFile("Data/TableScript.sql")
                                             .Execute(true, true, false));


            return(fluentConfig.BuildSessionFactory());
        }
        public virtual ISessionFactory CreateFactory()
        {
            return(Fluently.Configure()
                   .Database(this.Configurer)
                   .Mappings(m =>
            {
                var autoPersistenModel = AutoMap.Assemblies(this.GetAutomappingConfiguration,
                                                            this.SetAssemblyWithEntities());

                foreach (var type in this.SetIgnoreBase())
                {
                    autoPersistenModel.IgnoreBase(type);
                }

                autoPersistenModel
                .Conventions.Add(this.SetConvention())
                .UseOverridesFromAssembly(this.GetType().Assembly);

                foreach (var assembly in this.SetAssemblyWithEntities())
                {
                    autoPersistenModel.UseOverridesFromAssembly(assembly);
                }

                m.AutoMappings.Add(autoPersistenModel);
            })
                   .Mappings(m => m.HbmMappings.AddFromAssembly(this.GetType().Assembly))

#if DEBUG
                   .ExposeConfiguration(x => x.SetInterceptor(new SqlStatementInterceptor()))
#endif
                   .BuildSessionFactory());
        }
예제 #8
0
        private static Configuration Configure()
        {
            var config = Fluently.Configure()
                         .Database(
                SQLiteConfiguration.Standard.UsingFile("database").ShowSql()
                //MsSqlConfiguration.MsSql2008.ConnectionString(b => b.FromConnectionStringWithKey("db"))
                )
                         .Mappings(m =>
            {
                var model = AutoMap.Assemblies(new AutomappingConfiguration(), GetAssemblies());
                model.Conventions.Add(new SetEnumTypeConvention());
                model.Conventions.Add(new UseNewSqlDateTime2TypeConvention());
                model.Conventions.Add(new CollectionAccessConvention());
                model.Conventions.Add(new SqlTimestampConvention());
                model.Conventions.Add(new SetTableNameConvention());

                model.Conventions.Add(DefaultLazy.Never());
                m.AutoMappings.Add(model);
                m.AutoMappings.ExportTo("c:\\mapping");
                m.FluentMappings.ExportTo("c:\\mapping");
            })
                         .BuildConfiguration();

            // Generatre schema before each start
            var e = new SchemaExport(config);

            e.SetOutputFile(@"c:\mapping\a.sql");
            e.Execute(true, true, false);

            return(config);
        }
        public AutoPersistenceModel Generate()
        {
            var assemblies = _assembly != null
                ? new List <Assembly> {
                _assembly
            }
                : (from assembly in AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.ToLower().StartsWith("phoenix"))
                   from type in assembly.GetTypes()
                   where type.BaseType == typeof(PhoenixEntity)
                   select assembly).Distinct().ToList();

            var ass = _assembly ?? Assembly.GetAssembly(typeof(PhoenixEntity));


            var model = AutoMap.Assemblies(new PhoenixMappingConfiguration(), assemblies.ToArray())
                        .Conventions.Setup(this.GetConventions())
                        .IgnoreBase <PhoenixEntity>()
                        .IgnoreBase <Individual>()
                        .IgnoreBase <IndividualInvestor>()
                        .IgnoreBase(typeof(EntityWithTypedId <>))
                        .UseOverridesFromAssembly(ass);

            var asses =
                (from assembly in
                 AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.ToLower().StartsWith("phoenix"))
                 from type in assembly.GetTypes()
                 where type.GetInterfaces().Any(a => a == typeof(IAmExcludedFromNHibernateMapping)) && type.IsAbstract
                 select type);

            asses.ToList().Each(a => model.IgnoreBase(a));
            return(model);
        }
        public Configuration GetConfiguration()
        {
            var NHibernateAssembly = Assembly.Load("Naftan.Maintenance.NHibernate");
            var DomainAssembly     = Assembly.Load("Naftan.Maintenance.Domain");
            var CommonAssembly     = Assembly.Load("Naftan.Common");

            var msSqlDatabase = MsSqlConfiguration.MsSql2008
                                .UseOuterJoin()
                                .ShowSql()
                                .FormatSql()
                                // !!!ВНИМАНИЕ Аккуратнее с настойками базы данных для тестов. Если указать рабочую(боевую) базу данных, то ВСЕ РАБОЧИЕ ДАННЫЕ БУДУТ УДАЛЕНЫ !!!
                                .ConnectionString("data source = db2; initial catalog = maintenance_test; integrated security = SSPI;")
                                .UseReflectionOptimizer()
                                .AdoNetBatchSize(100);

            var automapping = AutoMap.Assemblies(new AutomappingConfig(), CommonAssembly, DomainAssembly)
                              .Conventions.AddAssembly(CommonAssembly)
                              .AddMappingsFromAssembly(NHibernateAssembly)
                              .UseOverridesFromAssembly(NHibernateAssembly);

            FluentConfiguration cfg = Fluently.Configure()
                                      .Database(msSqlDatabase)
                                      .Mappings(x => x.AutoMappings.Add(automapping)
                                                );

            var configuration = cfg.BuildConfiguration();

            return(configuration);
        }
예제 #11
0
        public static AutoPersistenceModel CreateMappings()
        {
            var cfg = new DbMapConfiguration();

            return(AutoMap.Assemblies(cfg, AppDomain.CurrentDomain.GetAssemblies())
                   .Conventions.Add(DefaultLazy.Never()));
            //.Where(t => t.Namespace == "CQRS2012");
        }
예제 #12
0
        private AutoPersistenceModel Generate()
        {
            AutoPersistenceModel mappings = AutoMap.Assemblies(
                new AutoMapConfiguration(), new Assembly[] { this.GetType().Assembly });

            mappings.UseOverridesFromAssembly(this.GetType().Assembly);


            return(mappings);
        }
예제 #13
0
 protected virtual AutoPersistenceModel AutomappingConventions()
 {
     return
         (AutoMap.Assemblies(new AutomappingConventionConfiguration(), _automapAssemblies)
          .Conventions.Add <SchemaTableConvention>()
          .Conventions.Add(new IdConvention(GetIncrementMultiplier()))
          .Conventions.Add <CascadeConvention>()
          .Conventions.Add <StringLengthConvention>()
          .Conventions.Add <VarBinaryLengthConvention>());
 }
 public AutoPersistenceModel Generate()
 {
     return
         (AutoMap.Assemblies(new FrameworkMappingConfiguration(), this.AutoMappingAssemblies)
          .Conventions
          .Setup(this.GetConventions())
          .IgnoreBase <Entity>()
          .IgnoreBase <DomainEntity>()
          .UseOverridesFromAssembly(this.OverrideAssembly)
          .UseOverridesFromAssembly(this.CoreFrameworkAssembly));
 }
예제 #15
0
        protected virtual AutoPersistenceModel CreateMappingModel()
        {
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

            var m = AutoMap.Assemblies(assemblies)
                    .Where(IsDomainEntity)
                    .IgnoreBase <EntityBase>()
                    .IgnoreBase <EntityWithIdBase>()
                    .IgnoreBase <EntityWithDescriptionBase>();

            return(m);
        }
예제 #16
0
        public AutoPersistenceModel Generate()
        {
            var mappings = AutoMap.Assemblies(
                new AutomappingConfiguration(),
                Assembly.Load("Oulanka.Domain"));

            mappings.IgnoreBase <Entity>();
            mappings.IgnoreBase(typeof(EntityWithTypedId <>));
            mappings.Conventions.Setup(GetConventions());
            mappings.UseOverridesFromAssemblyOf <AutoPersistenceModelGenerator>();
            return(mappings);
        }
        public FluentConfiguration BuildMapping(FluentConfiguration configuration, Type type, string nameSpace)
        {
            configuration = configuration
                            .Mappings(m =>
            {
                m.AutoMappings.Add(
                    AutoMap.Assemblies(Assembly.GetAssembly(type))
                    .UseOverridesFromAssembly(Assembly.GetAssembly(type))
                    .Conventions.AddAssembly(Assembly.GetAssembly(type))
                    .Where(t => t.Namespace != null && t.Namespace.StartsWith(nameSpace)));
                m.HbmMappings.AddFromAssembly(Assembly.GetAssembly(type));    // for stored procedures
            });

            return(configuration);
        }
예제 #18
0
        private static ISessionFactory BuildSessionFactory(string connectionString, FluentNHibernate.Conventions.IConvention[] conventions, Assembly[] assemblies, params Assembly[] overrides)
        {
            var persistenceModel = AutoMap.Assemblies(assemblies)
                                   .Conventions.Add(conventions)
                                   .Conventions.Add(Cache.Is(x => x.NonStrictReadWrite()))
                                   .IgnoreBase <Entity>()
                                   .Where(t => typeof(EntityWithTypedId <Guid>).IsAssignableFrom(t));


            if (overrides != null)
            {
                overrides.Each(a => persistenceModel.UseOverridesFromAssembly(a));
            }

            var config = Fluently.Configure()
                         .ProxyFactoryFactory <DefaultProxyFactoryFactory>()
                         .Database(
                MsSqlConfiguration.MsSql2008
                .ConnectionString(connectionString)
                .Provider <ContextDriverConnectionProvider>())
                         .CurrentSessionContext <LazySessionContext>()
                         .Cache(c => c.ProviderClass <SysCacheProvider>().UseSecondLevelCache().UseQueryCache())
                         .Mappings(m =>
            {
                m.AutoMappings.Add(persistenceModel);
                if (overrides != null)
                {
                    overrides.Each(a => m.HbmMappings.AddFromAssembly(a));
                }
            })
                         .BuildConfiguration();


#if DEBUG
            persistenceModel.WriteMappingsTo(AppDomain.CurrentDomain.BaseDirectory + @"Hbm");
            using (ISession session = config.BuildSessionFactory().OpenSession())
            {
                string syntax   = AppDomain.CurrentDomain.BaseDirectory + @"Hbm\{0}.sql";
                string filename = string.Format(syntax, session.Connection.Database);

                using (TextWriter stringWriter = new StreamWriter(filename))
                {
                    new SchemaExport(config).Execute(false, false, false, session.Connection, stringWriter);
                }
            }
#endif
            return(config.BuildSessionFactory());
        }
예제 #19
0
        protected NhibernateConfigurator(bool shouldMapDtos = true)
        {
            ShouldMapDtos = shouldMapDtos;

            var assembliesToMap                   = GetAssembliesToMap();
            var includeBaseTypes                  = GetIncludeBaseTypes();
            var ignoreBaseTypes                   = GetIgnoreBaseTypes();
            var discriminatedTypes                = GetDiscriminatedTypes();
            var mapDefaultConventions             = ShouldMapDefaultConventions();
            var assemblyWithAdditionalConventions = GetAssembliesWithAdditionalConventions();

            _configuration = new Configuration();
            _configuration.Configure();
            var autoPersistenceModel = AutoMap.Assemblies(
                new AutomappingConfiguration(discriminatedTypes.ToArray(), GetFuncToDetermineIfTypeIsDto(), ShouldMapDtos),
                assembliesToMap
                );

            includeBaseTypes.Each(x => autoPersistenceModel.IncludeBase(x));
            ignoreBaseTypes.Each(x => autoPersistenceModel.IgnoreBase(x));
            assembliesToMap.Each(x => autoPersistenceModel.UseOverridesFromAssembly(x));
            if (mapDefaultConventions)
            {
                DisableLazyLoadForDtosConvention.SetFuncToDetermineIfTypeIsDto(GetFuncToDetermineIfTypeIsDto());
                HasManyForDomainConvention.SetPropertyNameToBackingFieldNameFunc(GetPropertyNameToBackingFieldNameFunc());
                PrimaryKeyConvention.SetIdentityHiLoMaxLo(GetIdentityHiLoMaxLo());
                autoPersistenceModel.Conventions.AddFromAssemblyOf <PrimaryKeyConvention>();
            }
            assemblyWithAdditionalConventions.Each(x => autoPersistenceModel.Conventions.AddAssembly(x));

            if (ShouldDoubleQuoteTableNamesForDerivedClasses(_configuration))
            {
                _configuration.SetNamingStrategy(new QuoteTableNamesForDerivedClassesNamingStrategy());
            }

            var fluentConfiguration = Fluently.Configure(_configuration)
                                      .Mappings(x =>
            {
                var mappingsContainer = x.AutoMappings.Add(autoPersistenceModel);
                var exportNhibernateMappingsFolder = GetExportNhibernateMappingsFolder();
                if (!string.IsNullOrWhiteSpace(exportNhibernateMappingsFolder))
                {
                    mappingsContainer.ExportTo(exportNhibernateMappingsFolder);
                }
            });

            _sessionFactory = fluentConfiguration.BuildSessionFactory();
        }
예제 #20
0
        static NHConfig()
        {
            XmlConfigurator.Configure(LogManager.GetRepository(typeof(NHConfig).Assembly));
#if DEBUG
            HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
#endif

            var modelAssembly = typeof(NHConfig).Assembly;
            var configuration = Configuration = new Configuration();
            configuration.SetProperty(Environment.GenerateStatistics, "true");
            configuration.SetProperty(Environment.UseSqlComments, "true");
            configuration.SetProperty(Environment.ShowSql, "true");
            configuration.Configure();  // Configure from the hibernate.cfg.config

            // We have to replace |DataDirectory| as it is not supported on .NET Core
            var connString = configuration.Properties[Environment.ConnectionString];
            configuration.Properties[Environment.ConnectionString] =
                connString.Replace("|DataDirectory|",
                                   Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..")));

            var fluentConfig  = Fluently.Configure(configuration);
            var autoPestModel = AutoMap
                                .Assemblies(new AutomappingConfiguration(), new[] { modelAssembly })
                                .UseOverridesFromAssembly(modelAssembly)
                                .IgnoreBase <Entity>()
                                .Conventions.Add <CascadeConvention>()
                                .Conventions.Add(PrimaryKey.Name.Is(o => "Id"))
                                .Conventions.Add(ForeignKey.EndsWith("Id"));
            fluentConfig
            .Diagnostics(o => o.Enable(true))
            .Mappings(m =>
            {
                m.HbmMappings.AddFromAssembly(modelAssembly);
                m.AutoMappings.Add(autoPestModel);
#if DEBUG
                var mappingsDirecotry = Path.Combine(Directory.GetCurrentDirectory(), "Mappings");
                if (!Directory.Exists(mappingsDirecotry))
                {
                    Directory.CreateDirectory(mappingsDirecotry);
                }
                m.AutoMappings.ExportTo(mappingsDirecotry);
                m.FluentMappings.ExportTo(mappingsDirecotry);
#endif
            });

            SessionFactory = fluentConfig.BuildSessionFactory();
        }
예제 #21
0
 private static AutoPersistenceModel GetAutoPersistenceModel(List <Assembly> finalAssemblies)
 {
     return(AutoMap.Assemblies(new MrCMSMappingConfiguration(), finalAssemblies)
            .IgnoreBase <SystemEntity>()
            .IgnoreBase <SiteEntity>()
            .IncludeBase <Document>()
            .IncludeBase <Webpage>()
            .IncludeBase <UserProfileData>()
            .IncludeBase <Widget>()
            .IncludeBase <FormProperty>()
            .IncludeBase <FormPropertyWithOptions>()
            .IncludeBase <BatchJob>()
            .IncludeAppBases()
            .UseOverridesFromAssemblies(finalAssemblies)
            .Conventions.AddFromAssemblyOf <CustomForeignKeyConvention>()
            .IncludeAppConventions());
 }
예제 #22
0
        static NHConfig()
        {
            var modelAssembly = typeof(NHConfig).Assembly;
            var configuration = Configuration = new Configuration();

            configuration.SetProperty(Environment.GenerateStatistics, "true");
            configuration.SetProperty(Environment.UseSqlComments, "true");
            configuration.SetProperty(Environment.ShowSql, "true");
            configuration.Configure();  //configure from the web.config
            var fluentConfig  = Fluently.Configure(configuration);
            var autoPestModel = AutoMap
                                .Assemblies(new AutomappingConfiguration(), new[] { modelAssembly })
                                .UseOverridesFromAssembly(modelAssembly)
                                .IgnoreBase <Entity>()
                                .Conventions.Add <CascadeConvention>()
                                .Conventions.Add(PrimaryKey.Name.Is(o => "Id"))
                                .Conventions.Add(ForeignKey.EndsWith("Id"));

            fluentConfig
            .Diagnostics(o => o.Enable(true))
            .Mappings(m =>
            {
                m.HbmMappings.AddFromAssembly(modelAssembly);
                m.AutoMappings.Add(autoPestModel);
                var mappingsDirecotry = Path.Combine(Directory.GetCurrentDirectory(), "Mappings");
                if (!Directory.Exists(mappingsDirecotry))
                {
                    Directory.CreateDirectory(mappingsDirecotry);
                }
                m.AutoMappings.ExportTo(mappingsDirecotry);
                m.FluentMappings.ExportTo(mappingsDirecotry);
            });

            SessionFactory = fluentConfig.BuildSessionFactory();
            var schema = new SchemaExport(configuration);

            schema.Drop(false, true);
            schema.Create(false, true);

#if HIBERNATINGRHINOS
            HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
#endif
        }
예제 #23
0
        private AutoPersistenceModel GetAutoPersistenceModel()
        {
            var autoPersistenceModel = AutoMap.Assemblies(new AutomappingConfiguration(), _assemblyLocator.LocateDomainAssemblies().ToList().ToArray());

            // Add Pillar NHibernate conventions
            autoPersistenceModel = autoPersistenceModel.Conventions.AddFromAssemblyOf <AutomappingConfiguration> ();

            // To alllow two persistent classes with the same unqualified name
            //autoPersistenceModel = autoPersistenceModel.Conventions.Setup ( x => x.Add ( AutoImport.Never () ) );

            // Add conventions and overrides from infrastructure assebmlies
            var infrastructureAssebmlies = _assemblyLocator.LocateInfrastructureAssemblies();

            foreach (var infrastructureAssebmly in infrastructureAssebmlies)
            {
                autoPersistenceModel = autoPersistenceModel
                                       .Conventions.AddAssembly(infrastructureAssebmly)
                                       .UseOverridesFromAssembly(infrastructureAssebmly);
            }

            return(autoPersistenceModel);
        }
예제 #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            var persistenceModel = AutoMap.Assemblies(
                new AutoMappingConfiguration(),
                Enumerable.Empty <Assembly>());

            persistenceModel
            .Conventions.AddAssembly(Assembly.GetExecutingAssembly())
            .Conventions.Add(
                ConventionBuilder.Id.Always(x => x.Column("Id")),
                ForeignKey.EndsWith("Id"),
                ConventionBuilder.Property.When(
                    x => x.Expect(y => y.ReadOnly),
                    x => x.Access.CamelCaseField(FluentNHibernate.Conventions.Inspections.CamelCasePrefix.Underscore)
                    ),
                DynamicInsert.AlwaysTrue(),
                DynamicUpdate.AlwaysTrue(),
                OptimisticLock.Is(x => x.Version()))
            .UseOverridesFromAssemblyOf <Startup>()
            .AddEntityAssembly(typeof(Startup).Assembly)
            .AddMappingsFromAssemblyOf <Startup>();

            var sessionFactory = Fluently.Configure()
                                 .Database(MsSqlConfiguration.MsSql2008.ConnectionString(this.Configuration.GetConnectionString("Default")))
                                 .ExposeConfiguration(config =>
            {
                config.SetInterceptor(new AbpNHibernateInterceptor());
                new SchemaValidator(config).Validate();
            })
                                 .Mappings(
                m =>
            {
                m.AutoMappings.Add(persistenceModel);
            })
                                 .BuildSessionFactory();

            services.AddSingleton <ISessionFactory>(sessionFactory);
        }
        protected override FluentConfiguration InnerConfiguration(FluentConfiguration cfg)
        {
            if (this.AutomappingConfigurer == null)
            {
                return(cfg);
            }

            var autoMappingMetadataCollection = AutomappingConfigurer.GetAutomappingMetadata();
            var persistenceAssemblies         = autoMappingMetadataCollection
                                                .Select(metadata => Assembly.LoadFrom(metadata.AssemblyName));

            return(cfg.Mappings(
                       m => m.AutoMappings.Add(
                           AutoMap.Assemblies(new AutomappingConfigurationFilter(), persistenceAssemblies)
                           .Conventions
                           .Setup(c =>
            {
                //c.Add(PrimaryKey.Name.Is(x => "Id"));
                c.Add(ForeignKey.Format((x, t) => t.Name + "Id"));
                c.Add(DefaultLazy.Always());
                c.AddFromAssemblyOf <TablePluralizationConvention>();
            }))));
        }
        //public static IList<Type> IgnoredBaseTypes = new List<Type>
        //                                                 {

        //                                                     typeof(Person),typeof(Entity)

        //                                                 };

        //public static IList<Type> IncludeBaseTypes = new List<Type>
        //                                                 {
        //                                                     typeof (Employee)
        //                                                 };

        public static AutoPersistenceModel Generate(string[] domainAssemblies, string[] dalAssemblies)
        {
            AutoPersistenceModel mappings = AutoMap.Assemblies(
                new AutoMapConfiguration(), domainAssemblies.Select(Assembly.LoadFrom).ToArray());

            //foreach (Type ignoredBaseType in IgnoredBaseTypes)
            //{
            //    mappings.IgnoreBase(ignoredBaseType);
            //}
            //foreach (Type includeBaseType in IncludeBaseTypes)
            //{
            //    mappings.IncludeBase(includeBaseType);
            //}

            mappings.Conventions.Setup(GetConventions());


            foreach (string dalAssembly in dalAssemblies)
            {
                mappings.UseOverridesFromAssembly(Assembly.LoadFrom(dalAssembly));
            }

            return(mappings);
        }
        /// <summary>
        /// Save NHibernate Configuration only needed.
        /// </summary>
        /// <param name="config">NHibernate Configuration</param>
        protected override void PostProcessConfiguration(Configuration config)
        {
            assembliesForMapping    = FluentNHibernateMappingAssemblies.Select(name => Assembly.Load(name)).ToArray();
            assembliesForOverriding = FluentNHibernateOverridingAssemblies.Select(name => Assembly.Load(name)).ToArray();

            var assemblyInfoList     = assembliesForMapping.Union(assembliesForOverriding).Select(a => new FileInfo(a.Location)).ToList();
            var assemblyLastModified = assemblyInfoList.OrderByDescending(a => a.LastWriteTime).FirstOrDefault();

            currentPath = assemblyLastModified.DirectoryName;

            if (assemblyLastModified == null)
            {
                throw new DantasException("Assemblies for mapping entities is not configured yet.");
            }

            var formatter = new BinaryFormatter();
            var cache     = Path.Combine(assemblyLastModified.DirectoryName, "config.cache");

            if (File.Exists(cache))
            {
                var cacheInfo = new FileInfo(cache);
                needCreateConfig = assemblyLastModified.LastWriteTime > cacheInfo.LastWriteTime;
            }

            if (needCreateConfig)
            {
                Fluently.Configure(config)
                .Mappings(m =>
                {
                    m.MergeMappings();

                    if (UsingAutoMap)
                    {
                        AutoPersistenceModel model;

                        if (AutoMapConfig == null)
                        {
                            AutoMapConfig = new DantasAutomappingConfiguration();
                        }
                        if (ConventionBuilder == null)
                        {
                            ConventionBuilder = new ConventionBuilder();
                        }

                        m.AutoMappings.Add(
                            model = AutoMap.Assemblies(AutoMapConfig, assembliesForMapping)
                                    .Conventions.Setup(c =>
                                                       ConventionBuilder.Build(c)
                                                       )
                            );

                        foreach (var assembly in assembliesForOverriding)
                        {
                            model.UseOverridesFromAssembly(assembly);
                        }

                        if (ExportMappings)
                        {
                            m.AutoMappings.ExportTo(assemblyLastModified.DirectoryName);
                        }
                    }
                    else
                    {
                        foreach (var assembly in assembliesForMapping)
                        {
                            m.HbmMappings.AddFromAssembly(assembly);

                            m.FluentMappings.AddFromAssembly(assembly);
                        }
                    }
                }
                          ).BuildConfiguration();

                using (var stream = new FileStream(cache, FileMode.Create))
                {
                    formatter.Serialize(stream, config);
                }
            }
        }
        /// <summary>
        /// Main NHibernate configuration method.
        /// It configures NHibernate in an opinionated way, with an option to override various small NHibernate settings by overriding
        /// other virtual methods.
        /// This method can be overridden to completely customize NHibernate configuration.
        /// </summary>
        /// <param name="shouldMapDtos">See the constructor</param>
        /// <param name="configurationFileName">See the constructor</param>
        /// <param name="connectionString">See the constructor</param>
        /// <param name="sessionFactory">NHibernate session factory</param>
        /// <param name="configuration">NHibernate configuration</param>
        protected virtual void ConfigureNhibernate(
            bool shouldMapDtos,
            string configurationFileName,
            string connectionString,
            out ISessionFactory sessionFactory,
            out Configuration configuration
            )
        {
            configuration = new Configuration();
            if (string.IsNullOrWhiteSpace(configurationFileName))
            {
                configuration.Configure();
            }
            else
            {
                configuration.Configure(configurationFileName);
            }

            var assembliesToMap = GetAssembliesToMap();
            var isTypeDto       = GetIsTypeDtoFunc();

            var autoPersistenceModel = AutoMap.Assemblies(
                GetAutomappingConfiguration(shouldMapDtos, isTypeDto),
                assembliesToMap
                );

            GetIncludeBaseTypes().Each(x => autoPersistenceModel.IncludeBase(x));
            GetIgnoreBaseTypes().Each(x => autoPersistenceModel.IgnoreBase(x));
            assembliesToMap.Each(x => autoPersistenceModel.UseOverridesFromAssembly(x));

            _configureConventions();

            configuration.SetNamingStrategy(GetNamingStrategy());

            var fluentConfiguration = Fluently.Configure(configuration)
                                      .Mappings(x =>
            {
                var mappingsContainer            = x.AutoMappings.Add(autoPersistenceModel);
                var exportNhibernateMappingsPath = GetExportNhibernateMappingsPath();
                if (!string.IsNullOrWhiteSpace(exportNhibernateMappingsPath))
                {
                    mappingsContainer.ExportTo(exportNhibernateMappingsPath);
                }
            });

            if (!string.IsNullOrWhiteSpace(connectionString))
            {
                configuration.SetProperty(Environment.ConnectionString, connectionString);
            }

            AdditionalConfiguration(configuration);

            sessionFactory = fluentConfiguration.BuildSessionFactory();

            void _configureConventions()
            {
                if (ShouldUseDefaultConventions())
                {
                    DisableLazyLoadForDtosConvention.Initialize(isTypeDto);
                    HasManyConvention.Initialize(
                        GetCollectionCascadeInstanceAction(),
                        GetBackingFieldNameFromPropertyNameFunc(),
                        GetCollectionInstanceAccessAction()
                        );
                    PrimaryKeyConvention.Initialize(GetIdentityHiLoMaxLo());

                    var disabledConventions = GetDisabledConventions();
                    var conventionTypes     = Assembly.GetExecutingAssembly().GetTypes()
                                              .Where(type => typeof(IConvention).IsAssignableFrom(type) &&
                                                     !type.IsInterface &&
                                                     !disabledConventions.Contains(type))
                                              .ToList();

                    conventionTypes.Each(conventionType => autoPersistenceModel.Conventions.Add(conventionType));
                }

                GetAssembliesWithAdditionalConventions().Each(assembly => autoPersistenceModel.Conventions.AddAssembly(assembly));
                GetAdditionalConventions().Each(conventionType => autoPersistenceModel.Conventions.Add(conventionType));
            }
        }
예제 #29
0
 private static AutoPersistenceModel CreateMappings()
 {
     return(AutoMap
            .Assemblies(new AutoMappingConfigurationHelper(), System.Reflection.Assembly.GetCallingAssembly()));
 }