public static IServiceCollection ConfigureDataAccess(this IServiceCollection services, string connectionString)
        {
            var nhConfig = Fluently.Configure()
                           .Database(
                MsSqlConfiguration.MsSql2012.ConnectionString(connectionString)
                .DefaultSchema("dbo")
                .AdoNetBatchSize(20)
                .ShowSql()
                .FormatSql()
                .UseReflectionOptimizer()
                )
                           .Mappings(m =>
                                     m.FluentMappings
                                     .Conventions.Add(
                                         LazyLoad.Always(),
                                         DynamicUpdate.AlwaysTrue())
                                     .Conventions.Add <AssociationsMappingConvention>()
                                     .Conventions.Add <NotNullGuidTypeConvention>()
                                     .AddFromAssembly(Assembly.GetExecutingAssembly())

                                     );

            services.AddSingleton(nhConfig.BuildSessionFactory());
            services.AddScoped(sp =>
            {
                var sessionFactory = sp.GetRequiredService <ISessionFactory>();
                return(sessionFactory.OpenSession());
            });

            return(services);
        }
Exemplo n.º 2
0
 public MyAutoPersistenceModel()
 {
     this.AutoPersistenceModel = AutoMap.AssemblyOf <Entity>(new CustomAutomappingConfiguration())
                                 .IgnoreBase <Entity>()
                                 .Override <User>(map => map.IgnoreProperty(x => x.DisplayedName))
                                 .Override <Appointment>(map => map.IgnoreProperty(x => x.DateRange))
                                 .Override <IllnessPeriod>(map => map.IgnoreProperty(p => p.Duration))
                                 .Override <Role>(map => map.HasManyToMany(x => x.Tasks).Cascade.All())
                                 .Override <DbSetting>(map => map.Map(p => p.Key).Unique())
                                 .Override <Patient>(map =>
     {
         map.DynamicUpdate();
         map.IgnoreProperty(x => x.Age);
         map.Map(x => x.IsDeactivated).Default("0").Not.Nullable();
         map.HasMany <Bmi>(x => x.BmiHistory).KeyColumn("Patient_Id");
         map.HasMany <MedicalRecord>(x => x.MedicalRecords).KeyColumn("Patient_Id");
         map.HasMany <IllnessPeriod>(x => x.IllnessHistory).KeyColumn("Patient_Id");
         map.HasMany <Appointment>(x => x.Appointments).KeyColumn("Patient_Id");
     })
                                 .Override <Person>(map =>
     {
         map.Map(p => p.FirstName).Index("idx_person_FirstName");
         map.Map(p => p.LastName).Index("idx_person_LastName");
     })
                                 .Override <ApplicationStatistics>(map =>
     {
         map.Map(e => e.IsExported).Default("0").Not.Nullable();
         map.Map(e => e.Version).Default("\"3.0.3\"").Not.Nullable();
     })
                                 .Conventions.Add(DefaultCascade.SaveUpdate()
                                                  , DynamicUpdate.AlwaysTrue()
                                                  , DynamicInsert.AlwaysTrue()
                                                  , LazyLoad.Always());
 }
        public static ISessionFactory BuildSessionFactory(
            Configuration configuration,
            Assembly mappingsAssembly,
            Type idUserTypeGenericType)
        {
            // todo: check args

            return(Fluently.Configure(configuration)
                   .Mappings(m => m.FluentMappings.AddFromAssembly(mappingsAssembly)
                             .Conventions.Add(ForeignKey.Format((p, t) =>
            {
                if (p == null)
                {
                    return t.Name.Underscore() + "_id";
                }

                return p.Name.Underscore() + "_id";
            }))
                             .Conventions.Add(LazyLoad.Never())
                             .Conventions.Add(Table.Is(x => x.TableName.Underscore().ToUpper()))
                             .Conventions.Add(ConventionBuilder.Property.Always(x => x.Column(x.Property.Name.Underscore())))
                             .Conventions.Add(new IdUserTypeConvention(idUserTypeGenericType))
                             )
                   .BuildSessionFactory());
        }
Exemplo n.º 4
0
        /// <summary>
        /// Fluent NHibernate 에서 제공하는 Convention 설정에 따른 <see cref="IConvention"/> 인스턴스를 빌드하여 제공합니다.
        /// </summary>
        /// <param name="options">ConventionOptions 인스턴스</param>
        /// <returns>Convention 설정 정보를 기초로 만든 <see cref="IConvention"/>의 인스턴스 배열</returns>
        public static IList <IConvention> ToConventions(ConventionOptions options)
        {
            options.ShouldNotBeNull("optioons");

            if (IsDebugEnabled)
            {
                log.Debug("ConventionOptions 정보로 IConvention[]을 빌드합니다...  " + options);
            }

            var conventions = new List <IConvention>();

            conventions.Add((options.DefaultLazy) ? LazyLoad.Always() : LazyLoad.Never());

            if (options.DynamicInsert)
            {
                conventions.Add(FluentNHibernate.Conventions.Helpers.DynamicInsert.AlwaysTrue());
            }
            if (options.DynamicUpdate)
            {
                conventions.Add(FluentNHibernate.Conventions.Helpers.DynamicUpdate.AlwaysTrue());
            }

            if (options.TableNamePrefix.IsNotWhiteSpace())
            {
                conventions.Add(Table.Is(x => options.TableNamePrefix + x.EntityType.Name));
            }
            else if (options.TableNamePrefix.IsNotWhiteSpace())
            {
                conventions.Add(Table.Is(x => x.EntityType.Name + options.TableNameSurfix));
            }
            else
            {
                conventions.Add(Table.Is(x => x.EntityType.Name));
            }

            if (options.PrimaryKeyName.IsNotWhiteSpace())
            {
                conventions.Add(PrimaryKey.Name.Is(x => options.PrimaryKeyName));
            }
            else if (options.PrimaryKeySurfix.IsNotWhiteSpace())
            {
                conventions.Add(PrimaryKey.Name.Is(x => x.EntityType.Name + options.PrimaryKeySurfix));
            }

            if (options.ForeignKeySurfix.IsNotWhiteSpace())
            {
                conventions.Add(ForeignKey.EndsWith(options.ForeignKeySurfix));

                conventions.Add(ConventionBuilder.HasMany.Always(x => x.Key.Column(x.EntityType.Name + options.ForeignKeySurfix)));
                conventions.Add(ConventionBuilder.Reference.Always(x => x.Column(x.Property.Name + options.ForeignKeySurfix)));

                conventions.Add(ConventionBuilder.HasManyToMany.Always(x => {
                    x.Key.Column(x.EntityType.Name + options.PrimaryKeySurfix);
                    x.Relationship.Column(x.ChildType.Name +
                                          options.ForeignKeySurfix);
                }));
            }

            return(conventions);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Starts LiteDB database using full parameters
 /// </summary>
 public LiteDatabase(IDiskService diskService, ushort version = 0)
 {
     _engine = new LazyLoad<DbEngine>(
         () => new DbEngine(diskService, _log),
         () => this.InitializeMapper(),
         () => this.UpdateDbVersion(version));
 }
Exemplo n.º 6
0
        public LitePlatformWindowsStore()
        {
            _fileHandler       = new LazyLoad <IFileHandler>(() => new FileHandlerWindowsStore(Windows.Storage.ApplicationData.Current.LocalFolder));
            _reflectionHandler = new LazyLoad <IReflectionHandler>(() => new ExpressionReflectionHandler());

            AddNameCollectionToMapper();
        }
Exemplo n.º 7
0
 /// <summary>
 /// Initialize database using any read/write Stream (like MemoryStream)
 /// </summary>
 public LiteDatabase(Stream stream, ushort version = 0)
 {
     _engine = new LazyLoad<DbEngine>(
         () => new DbEngine(new StreamDiskService(stream), _log),
         () => this.InitializeMapper(),
         () => this.UpdateDbVersion(version));
 }
Exemplo n.º 8
0
        private DataManager()
        {
            _sessionFactory = Fluently.Configure()
                              .Database(() =>
            {
                var result = MsSqlConfiguration.MsSql2012.ConnectionString(c => c.FromConnectionStringWithKey("YokogawaData"));

                if (Config.Current.ShowSql)
                {
                    result.ShowSql();
                }

                return(result);
            })
                              .Mappings(m =>
            {
                m.FluentMappings
                .AddFromAssembly(GetType().Assembly)
                .Conventions.Add(
                    ForeignKey.EndsWith("ID"),
                    LazyLoad.Always()
                    );
            })
                              .CurrentSessionContext <ThreadStaticSessionContext>()
                              .BuildSessionFactory();
        }
Exemplo n.º 9
0
        public void InitializeFactory()
        {
            if (!_isInitialized)
            {
                FluentConfiguration conf = Fluently.Configure()
                                           .Database(MySQLConfiguration.Standard.ConnectionString(_connection))
                                           .CurrentSessionContext <ThreadLocalSessionContext>()
                                           .Mappings(map =>
                {
                    map.FluentMappings.Conventions.Add(
                        new EnumConvention(),
                        new CascadeAllConvention(),
                        new ColumnNameConvention(),
                        new TableNameConvention(),
                        LazyLoad.Never()
                        );
                    map.FluentMappings.AddFromAssemblyOf <EmployeeMap>();
                })
                                           .ExposeConfiguration(x =>
                {
                    x.SetInterceptor(new SqlStatementInterceptor());
                    x.EventListeners.PreInsertEventListeners = new IPreInsertEventListener[] { new EntityService() };
                });

                if (!_writeOnly)
                {
                    conf.ExposeConfiguration(config => new SchemaUpdate(conf.BuildConfiguration()).Execute(true, true));
                }

                _sessionFactory = conf.BuildSessionFactory();

                _isInitialized = true;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Starts LiteDB database using a connection string for filesystem database
        /// </summary>
        public LiteDatabase(string connectionString)
        {
            var conn = new ConnectionString(connectionString);
            var version = conn.GetValue<ushort>("version", 0);
            var encrypted = !StringExtensions.IsNullOrWhiteSpace(conn.GetValue<string>("password", null));

            _engine = new LazyLoad<DbEngine>(
                () => new DbEngine(encrypted ? new EncryptedDiskService(conn, _log) : new FileDiskService(conn, _log), _log),
                () => this.InitializeMapper(),
                () => this.UpdateDbVersion(version));
        }
Exemplo n.º 11
0
        public void Set(DateTime LastTimeUpdate, DateTime LastTimeOnServer, CommonDll.Structs.F_HR.HR Set_HR)
        {
            Set_HR            = (CommonDll.Structs.F_HR.HR)base.Set(ImportProtocol.HR, Set_HR, true, out TimeSpan TimeOnSetted);
            ImportProtocol.HR = Set_HR;

            LazyLoad.LazyLoading(this, MethodBase.GetCurrentMethod().Name, new Action(() =>
            {
                treeListView_HRMain1.Set(LastTimeUpdate, LastTimeOnServer);
                treeListView_Groups1.Set(LastTimeUpdate, LastTimeOnServer);
            }));
        }
Exemplo n.º 12
0
        public LitePlatformWindowsStore(StorageFolder folder)
        {
#if WINDOWS_UWP
            _fileHandler = new LazyLoad <IFileHandler>(() => new FileHandlerUWP(folder));
#else
            _fileHandler = new LazyLoad <IFileHandler>(() => new FileHandlerWindowsStore(folder));
#endif
            _reflectionHandler = new LazyLoad <IReflectionHandler>(() => new ExpressionReflectionHandler());

            AddNameCollectionToMapper();
        }
Exemplo n.º 13
0
		public void TestLazyLoad(){
			int i = 1;
			LazyLoad<int> t = new LazyLoad<int>(() => i);
			i = 2;
			Assert.AreEqual(2, t);
			i = 3;
			Assert.AreEqual(2, t);
			t.Reset();
			Assert.AreEqual(3, t);

		}
Exemplo n.º 14
0
 public Bag(CodeFileBuilder builder)
 {
     _builder      = builder;
     _where        = new Where(builder);
     _orderBy      = new OrderBy(builder);
     _cascade      = new Cascade(builder);
     _fetch        = new Fetch(builder);
     _inverse      = new Inverse(builder);
     _table        = new Table(builder);
     _keyColumn    = new KeyColumn(builder);
     _lazyLoad     = new LazyLoad(builder);
     _cacheBuilder = new CacheBuilder(builder);
 }
Exemplo n.º 15
0
 private static Action <FluentNHibernate.Conventions.IConventionFinder> GetConventions()
 {
     return(mappings =>
     {
         mappings.Add <PrimaryKeyConvention>();
         mappings.Add <TableNameConvention>();
         mappings.Add <EnumConvention>();
         mappings.Add(ForeignKey.EndsWith("Id"));
         mappings.Add(DefaultCascade.None());
         mappings.Add(DefaultAccess.Property());
         mappings.Add(DefaultLazy.Always());
         mappings.Add(LazyLoad.Always());
     });
 }
Exemplo n.º 16
0
        private void HandleMappings(MappingConfiguration cfg)
        {
            cfg.HbmMappings.AddFromAssemblyOf <SessionManager <T> >();

            cfg.FluentMappings
            .AddFromAssembly(GetType().Assembly)
            .Conventions.AddAssembly(GetType().Assembly)
            .Conventions.Add(
                AutoImport.Always(),
                ForeignKey.EndsWith("ID"),
                LazyLoad.Always(),
                DefaultCascade.None(),
                DynamicInsert.AlwaysTrue(),
                DynamicUpdate.AlwaysTrue());
        }
Exemplo n.º 17
0
        private ISessionFactory BuildSessionFactory(Configuration configuration, Assembly mappingsAssembly)
        {
            return(Fluently.Configure(configuration)
                   .Mappings(m => m.FluentMappings.AddFromAssembly(mappingsAssembly)
                             .Conventions.Add(ForeignKey.Format((p, t) =>
            {
                if (p == null)
                {
                    return t.Name.Underscore() + "_id";
                }

                return p.Name.Underscore() + "_id";
            }))
                             .Conventions.Add(LazyLoad.Never())
                             .Conventions.Add(Table.Is(x => x.TableName.Underscore().ToUpper()))
                             .Conventions.Add(ConventionBuilder.Property.Always(x => x.Column(x.Property.Name.Underscore())))
                             .Conventions.Add(typeof(IdUserTypeConvention), new IdUserTypeConvention(this.GetIdUserTypeGeneric()))
                             )
                   .BuildSessionFactory());
        }
Exemplo n.º 18
0
 private static FluentConfiguration GetFluentConfigurationForDatabase(string connectionString)
 {
     return(Fluently.Configure()
            .Database(
                MsSqlConfiguration.MsSql2012
                .Provider <HybridStorageDriverConnectionProvider>()
                .ConnectionString(connectionString)
                .DefaultSchema("dbo")
                .AdoNetBatchSize(20)
                .ShowSql()
                .FormatSql()
                .UseReflectionOptimizer()
                )
            .Mappings(m =>
                      m.FluentMappings
                      .Conventions.Add(
                          LazyLoad.Always(),
                          DynamicUpdate.AlwaysTrue())
                      .Conventions.Add <AssociationsMappingConvention>()
                      .Conventions.Add <NotNullGuidTypeConvention>()
                      .AddFromAssembly(Assembly.GetExecutingAssembly())));
 }
Exemplo n.º 19
0
 public void BeforeEachTest()
 {
     _builder  = new CodeFileBuilder();
     _lazyLoad = new LazyLoad(_builder);
 }
Exemplo n.º 20
0
 /// <summary>
 /// Constructor which accepts a default directory for all files.
 /// Default directory can be overridden by specifying a full path when opening the database.
 /// </summary>
 /// <param name="defaultPath">Default path where files will be placed.</param>
 public LitePlatformNetCore(string defaultPath)
 {
     _fileHandler = new LazyLoad <IFileHandler>(() => new FileHandler(defaultPath));
     AddNameCollectionToMapper();
 }
Exemplo n.º 21
0
 public Nolazy()
 {
     Content = new LazyLoad <string>(this, "Content");
 }