public void CriarSchema() { // Apenas no Init da Aplicação var config = new Configuration(); config.DataBaseIntegration(c => { c.Dialect<MsSql2012Dialect>(); c.ConnectionStringName = "ExemploNH"; c.LogFormattedSql = true; c.LogSqlInConsole = true; c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; }); var modelMapper = new ModelMapper(); modelMapper.AddMappings(typeof (ProdutoMap).Assembly.GetExportedTypes()); config.AddDeserializedMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities(), "Domain"); ISessionFactory sessionFactory = config.BuildSessionFactory(); // NOTE: Estudar framework FluentMigration var schemaExport = new SchemaExport(config); schemaExport.Create(true, true); }
protected override HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class<Author>(rc => { rc.Id(x => x.Id, m => m.Generator(Generators.Identity)); rc.Property(x => x.Name); rc.ManyToOne(x => x.Publisher, m => m.Cascade(Mapping.ByCode.Cascade.All)); rc.Set(x => x.Books, m => { m.Cascade(Mapping.ByCode.Cascade.All); m.Lazy(CollectionLazy.Lazy); }, r => r.OneToMany()); }); mapper.Class<Book>(rc => { rc.Id(x => x.Id, m => m.Generator(Generators.Identity)); rc.Property(x => x.Title); rc.ManyToOne(x => x.Author); }); mapper.Class<Publisher>(rc => { rc.Id(x => x.Id, m => m.Generator(Generators.Identity)); rc.Property(x => x.Name); rc.Set(x => x.Authors, m => m.Cascade(Mapping.ByCode.Cascade.All), r => r.OneToMany()); }); return mapper.CompileMappingForAllExplicitlyAddedEntities(); }
private static void InitializeSessionFactory() { if (sessionFactory == null) { lock (mutex) { if (sessionFactory == null) { configuration = new Configuration(); configuration.DataBaseIntegration(db => { db.ConnectionString = connectionString; db.Dialect<MsSql2008Dialect>(); db.Driver<SqlClientDriver>(); db.Timeout = 20; db.LogFormattedSql = Config.LogSql; db.LogSqlInConsole = Config.LogSql; }); var modelMapper = new ModelMapper(); modelMapper.AddMappings(ExportedTypes); var mappingDocument = modelMapper.CompileMappingForAllExplicitlyAddedEntities(); configuration.AddMapping(mappingDocument); sessionFactory = configuration.BuildSessionFactory(); } } } }
public void TestGenerators() { var mapper = new ModelMapper(); mapper.Class<A>(e => { e.Id(c => c.Id, c => c.Generator(Generators.Counter)); }); mapper.Class<B>(e => { e.Id(c => c.Id, c => c.Generator(Generators.UUIDHex)); }); mapper.Class<C>(e => { e.Id(c => c.Id, c => c.Generator(Generators.UUIDString)); }); mapper.Class<D>(e => { e.Id(c => c.Id, c => c.Generator(Generators.Increment)); }); mapper.Class<E>(e => { e.Id(c => c.Id, c => c.Generator(Generators.Select)); }); mapper.Class<F>(e => { e.Id(c => c.Id, c => c.Generator(Generators.SequenceHiLo)); }); mapper.Class<G>(e => { e.Id(c => c.Id, c => c.Generator(Generators.SequenceIdentity)); }); mapper.Class<H>(e => { e.Id(c => c.Id, c => c.Generator(Generators.Table)); }); mapper.Class<I>(e => { e.Id(c => c.Id, c => c.Generator(Generators.TriggerIdentity)); }); var hbmMapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); Assert.AreEqual(hbmMapping.RootClasses.Single(x => x.Name == typeof(A).Name).Id.generator.@class, Generators.Counter.Class); Assert.AreEqual(hbmMapping.RootClasses.Single(x => x.Name == typeof(B).Name).Id.generator.@class, Generators.UUIDHex.Class); Assert.AreEqual(hbmMapping.RootClasses.Single(x => x.Name == typeof(C).Name).Id.generator.@class, Generators.UUIDString.Class); Assert.AreEqual(hbmMapping.RootClasses.Single(x => x.Name == typeof(D).Name).Id.generator.@class, Generators.Increment.Class); Assert.AreEqual(hbmMapping.RootClasses.Single(x => x.Name == typeof(E).Name).Id.generator.@class, Generators.Select.Class); Assert.AreEqual(hbmMapping.RootClasses.Single(x => x.Name == typeof(F).Name).Id.generator.@class, Generators.SequenceHiLo.Class); Assert.AreEqual(hbmMapping.RootClasses.Single(x => x.Name == typeof(G).Name).Id.generator.@class, Generators.SequenceIdentity.Class); Assert.AreEqual(hbmMapping.RootClasses.Single(x => x.Name == typeof(H).Name).Id.generator.@class, Generators.Table.Class); Assert.AreEqual(hbmMapping.RootClasses.Single(x => x.Name == typeof(I).Name).Id.generator.@class, Generators.TriggerIdentity.Class); }
/// <summary> /// Creates session factory /// </summary> /// <param name="configurationReader">configuration reader</param> /// <returns></returns> private static ISessionFactory CreateSessionFactory(IConfigurationReader configurationReader) { var configuration = new NHibernate.Cfg.Configuration(); configuration.SessionFactoryName("Jumblocks Blog"); configuration.DataBaseIntegration(db => { db.Dialect<MsSql2008FixedDialect>(); db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionString = configurationReader.ConnectionStrings["BlogDb"].ConnectionString; db.BatchSize = 100; //for testing db.LogFormattedSql = true; db.LogSqlInConsole = true; db.AutoCommentSql = true; }); var mapper = new ModelMapper(); mapper.AddMapping<BlogPostMap>(); mapper.AddMapping<BlogUserMap>(); mapper.AddMapping<ImageReferenceMap>(); mapper.AddMapping<TagMap>(); mapper.AddMapping<SeriesMap>(); mapper.AddMapping<UserMap>(); mapper.AddMapping<RoleMap>(); mapper.AddMapping<OperationMap>(); configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); configuration.CurrentSessionContext<WebSessionContext>(); return configuration.BuildSessionFactory(); }
public static void AddNHibernateSessionFactory(this IServiceCollection services) { // By default NHibernate looks for hibernate.cfg.xml // otherwise for Web it will fallback to web.config // we got one under wwwroot/web.config Configuration config = new Configuration(); config.Configure(); // Auto load entity mapping class ModelMapper mapper = new ModelMapper(); mapper.AddMappings(Assembly.GetAssembly(typeof(Employee)).GetExportedTypes()); HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); config.AddDeserializedMapping(mapping, "NHibernate.Mapping"); SchemaMetadataUpdater.QuoteTableAndColumns(config); // Drop & Recreate database schema new SchemaExport(config).Drop(false, true); new SchemaExport(config).Create(false, true); // Register services services.AddSingleton<ISessionFactory>(provider => config.BuildSessionFactory()); services.AddTransient<ISession>(provider => services.BuildServiceProvider().GetService<ISessionFactory>().OpenSession()); }
public void TestConnection() { var cfg = new Configuration() .DataBaseIntegration(db => { db.ConnectionString = "Server=127.0.0.1;Database=troyanda;Uid=postgres;Pwd=qwerty;"; db.Dialect<PostgreSQL94Dialect>(); db.SchemaAction = SchemaAutoAction.Validate; }); var types = typeof (Cars).Assembly.GetExportedTypes(); /* Add the mapping we defined: */ var mapper = new ModelMapper(); mapper.AddMappings(types); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); cfg.AddMapping(mapping); /* Create a session and execute a query: */ using (ISessionFactory factory = cfg.BuildSessionFactory()) using (ISession session = factory.OpenSession()) using (ITransaction tx = session.BeginTransaction()) { var car = session.Get<Cars>((long)1); var worker = new WorkerServices(cfg, session); var result = worker.GetItemsPresenterForEntity(typeof (Sector)); //session.Save() tx.Commit(); } }
public void SpecifiedForeignKeyNameInByCodeMappingIsUsedInGeneratedSchema() { var mapper = new ModelMapper(); // Generates a schema in which a Person record cannot be created unless an Employee // with the same primary key value already exists. The Constrained property of the // one-to-one mapping is required to create the foreign key constraint on the Person // table, and the optional ForeignKey property is used to name it; otherwise a // generated name is used mapper.Class<Person>(rc => { rc.Id(x => x.Id, map => map.Generator(Generators.Foreign<Employee>(p => p.Person))); rc.Property(x => x.Name); rc.OneToOne(x => x.Employee, map => { map.Constrained(true); map.ForeignKey(ForeignKeyName); }); }); mapper.Class<Employee>(rc => { rc.Id(x => x.Id); rc.OneToOne(x => x.Person, map => { }); }); var script = new StringBuilder(); var cfg = new Configuration(); cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); new SchemaExport(cfg).Execute(s => script.AppendLine(s), false, false); script.ToString().Should().Contain(string.Format("constraint {0}", ForeignKeyName)); }
private static void InitNHibernate() { lock (LockObject) { if (_sessionFactory == null) { // Создание NHibernate-конфигурации приложения на основании описаний из web.config. // После этого вызова, в том числе, из сборки будут извлечены настройки маппинга, // заданные в xml-файлах. var configure = new Configuration().Configure(); // Настройка маппинга, созданного при помощи mapping-by-code var mapper = new ModelMapper(); mapper.AddMappings(new List<Type> { // Перечень классов, описывающих маппинг typeof (DocumentTypeMap), typeof (DocumentMap), typeof (DocumentWithVersionMap), }); // Добавление маппинга, созданного при помощи mapping-by-code, // в NHibernate-конфигурацию приложения configure.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), null); //configure.LinqToHqlGeneratorsRegistry<CompareValuesGeneratorsRegistry>(); //configure.LinqToHqlGeneratorsRegistry<InGeneratorRegistry>(); configure.DataBaseIntegration(x => { x.LogSqlInConsole = true; x.LogFormattedSql = true; }); _sessionFactory = configure.BuildSessionFactory(); } } }
private static HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.AddMappings(typeof(SessionHelper).Assembly.GetExportedTypes()); HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); return mapping; }
protected override HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.BeforeMapClass += (inspector, type, map) => map.Id(x=> x.Generator(Generators.GuidComb)); mapper.Class<Foo>(mc => { mc.Id(x => x.Id); mc.Bag(x => x.Bars, map => { map.Inverse(true); map.Cascade(Mapping.ByCode.Cascade.All); map.Key(km => { km.Column("FooId"); km.OnDelete(OnDeleteAction.Cascade); }); }, rel => rel.OneToMany()); }); mapper.Class<Bar>(mc => { mc.Id(x => x.Id); mc.ManyToOne(x=> x.Foo, map=> map.Column("FooId")); }); var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); return mappings; }
public static Configuration BuildConfiguration(string connStr) { var cfg = new Configuration(); // See http://fabiomaulo.blogspot.com/2009/07/nhibernate-configuration-through.html cfg.DataBaseIntegration(db => { db.Driver<SqlClientDriver>(); db.Dialect<MsSql2012Dialect>(); db.ConnectionString = connStr; // db.ConnectionStringName = "ConnStr"; db.HqlToSqlSubstitutions = "true 1, false 0, yes 'Y', no 'N'"; // See http://geekswithblogs.net/lszk/archive/2011/07/12/showing-a-sql-generated-by-nhibernate-on-the-vs-build-in.aspx //db.LogSqlInConsole = true; // Remove if using Log4Net //db.LogFormattedSql = true; //db.AutoCommentSql = true; db.SchemaAction = SchemaAutoAction.Validate; // This correspond to "hbm2ddl.validate", see http://nhforge.org/blogs/nhibernate/archive/2008/11/23/nhibernate-hbm2ddl.aspx }); var mapper = new ModelMapper(); mapper.Class<Parent>(map => { map.Id(x => x.Id, m => { m.Generator(Generators.GuidComb); m.UnsavedValue(Guid.Empty); }); map.Version(x => x.RowVersion, m => m.UnsavedValue(0)); map.Property(x => x.Description); }); cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); return cfg; }
public void TestMapElementElement() { var mapper = new ModelMapper(); mapper.Class<ClassWithMapElementElement>( c => { c.Lazy(false); c.Id(id => id.Id, id => id.Generator(Generators.Identity)); c.Map( m => m.Map, col => { col.Table("element_element"); col.Key(k => k.Column("id")); }, key => key.Element(e => e.Column("key")), element => element.Element(e => e.Column("element"))); }); var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); var hbmClass = mappings.RootClasses.FirstOrDefault(c => c.Name == typeof (ClassWithMapElementElement).Name); var hbmMap = hbmClass.Properties.OfType<HbmMap>().SingleOrDefault(); Assert.That(hbmMap, Is.Not.Null); Assert.That(hbmMap.Item, Is.TypeOf<HbmMapKey>()); Assert.That(hbmMap.Item1, Is.TypeOf<HbmElement>()); }
public static void NHibernateConfiguration(TestContext context) { log4net.Config.XmlConfigurator.Configure(); Configuration = new Configuration(); // lendo o arquivo hibernate.cfg.xml Configuration.Configure(); FilterDefinition filterDef = new FilterDefinition( "Empresa","EMPRESA = :EMPRESA", new Dictionary<string, IType>() {{"EMPRESA", NHibernateUtil.Int32}}, false); Configuration.AddFilterDefinition(filterDef); filterDef = new FilterDefinition( "Ativa", "ATIVO = 'Y'", new Dictionary<string, IType>(), false); Configuration.AddFilterDefinition(filterDef); // Mapeamento por código var mapper = new ModelMapper(); mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes()); HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); Configuration.AddMapping(mapping); // Gerar o XML a partir do mapeamento de codigo. //var mappingXMl = mapping.AsString(); // Mapeamento por arquivo, in resource. Configuration.AddAssembly(Assembly.GetExecutingAssembly()); // Gerando o SessionFactory SessionFactory = Configuration.BuildSessionFactory(); }
/// <summary> /// Configures the storage with the user supplied persistence configuration /// Azure tables are created if requested by the user /// </summary> /// <param name="config"></param> /// <param name="connectionString"></param> /// <param name="createSchema"></param> /// <returns></returns> public static Configure AzureSubcriptionStorage(this Configure config, string connectionString, bool createSchema, string tableName) { var cfg = new Configuration() .DataBaseIntegration(x => { x.ConnectionString = connectionString; x.ConnectionProvider<TableStorageConnectionProvider>(); x.Dialect<TableStorageDialect>(); x.Driver<TableStorageDriver>(); }); SubscriptionMap.TableName = tableName; var mapper = new ModelMapper(); mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes()); var faultMappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); cfg.AddMapping(faultMappings); if (createSchema) { new SchemaExport(cfg).Execute(true, true, false); } var sessionSource = new SubscriptionStorageSessionProvider(cfg.BuildSessionFactory()); config.Configurer.RegisterSingleton<ISubscriptionStorageSessionProvider>(sessionSource); config.Configurer.ConfigureComponent<SubscriptionStorage>(DependencyLifecycle.InstancePerCall); return config; }
public void ComponentMappingJustOnceDemo() { var mapper = new ModelMapper(); mapper.Component<Name>(comp => { comp.Property(name => name.First); comp.Property(name => name.Last); }); mapper.Component<Address>(comp => { comp.Property(address => address.CivicNumber); comp.Property(address => address.Street); }); mapper.Class<Person1>(cm => { cm.Id(person => person.Id, map => map.Generator(Generators.HighLow)); cm.Property(person => person.Test); cm.Component(person => person.Name, comp => { }); cm.Component(person => person.Address, comp => { }); }); var hbmMapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); var hbmClass = hbmMapping.RootClasses[0]; var hbmComponents = hbmClass.Properties.OfType<HbmComponent>(); hbmComponents.Should().Have.Count.EqualTo(2); hbmComponents.Select(x => x.Name).Should().Have.SameValuesAs("Name","Address"); }
private HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.BeforeMapClass += (mi, t, map) => map.Id(x => x.Generator(Generators.GuidComb)); mapper.Class<Parent>(rc => { rc.Id(p => p.Id); rc.Property(p => p.ParentCode, m => m.Unique(true)); rc.Property(p => p.Name); rc.Bag(p => p.Children, m => { m.Key(km => { km.Column(cm => cm.Name("ParentParentCode")); km.PropertyRef(pg => pg.ParentCode); }); m.Inverse(true); m.Cascade(Mapping.ByCode.Cascade.Persist); }, rel => rel.OneToMany()); }); mapper.Class<Child>(rc => { rc.Id(p => p.Id); rc.Property(p => p.Name); rc.ManyToOne<Parent>(p => p.Parent, m => { m.Column("ParentParentCode"); m.PropertyRef("ParentCode"); }); }); return mapper.CompileMappingForAllExplicitlyAddedEntities(); }
protected override HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class<Order>(rc => { rc.Table("Orders"); rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb)); rc.Property(x => x.Name); rc.Set(x => x.OrderLines, m => { m.Inverse(true); m.Key(k => { k.Column("OrderId"); k.NotNullable(true); }); m.Cascade(Mapping.ByCode.Cascade.All.Include(Mapping.ByCode.Cascade.DeleteOrphans)); m.Access(Accessor.NoSetter); }, m => m.OneToMany()); }); mapper.Class<OrderLine>(rc => { rc.Table("OrderLines"); rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb)); rc.Property(x => x.Name); rc.ManyToOne(x => x.Order, m => m.Column("OrderId")); }); return mapper.CompileMappingForAllExplicitlyAddedEntities(); }
static SessionFactory() { var connectionString = @"Data Source=.\sqlexpress2014;Initial Catalog=BlogDatabase;Integrated Security=True"; var configuration = new Configuration(); configuration.DataBaseIntegration( x => { x.ConnectionString = connectionString; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2012Dialect>(); }); configuration.SetProperty(Environment.UseQueryCache, "true"); configuration.SetProperty(Environment.UseSecondLevelCache, "true"); configuration.SetProperty(Environment.CacheProvider, typeof(SysCacheProvider).AssemblyQualifiedName); var mapper = new ModelMapper(); mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes()); mapper.BeforeMapBag += (modelInspector, member1, propertyCustomizer) => { propertyCustomizer.Inverse(true); propertyCustomizer.Cascade(Cascade.All | Cascade.DeleteOrphans); }; mapper.BeforeMapManyToOne += (modelInspector, member1, propertyCustomizer) => { propertyCustomizer.NotNullable(true); }; mapper.BeforeMapProperty += (inspector, member, customizer) => customizer.NotNullable(true); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); configuration.AddMapping(mapping); sessionFactory = configuration.BuildSessionFactory(); }
static Configuration AddLoquaciousMappings(Configuration nhConfiguration) { ModelMapper mapper = new ModelMapper(); mapper.AddMappings(typeof(OrderSagaDataLoquacious).Assembly.GetTypes()); nhConfiguration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); return nhConfiguration; }
void ApplyMappings(Configuration config) { var mapper = new ModelMapper(); mapper.AddMapping<OutboxEntityMap>(); config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); }
private HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class<User>(rt => { rt.Id(x => x.Id, map => map.Generator(Generators.Guid)); rt.Property(x => x.Name); rt.Set(x => x.Roles, map => { map.Table("UsersToRoles"); map.Inverse(true); map.Key(km => km.Column("UserId")); }, rel => rel.ManyToMany(mm => { mm.Column("RoleId"); mm.ForeignKey("FK_RoleInUser"); })); }); mapper.Class<Role>(rt => { rt.Id(x => x.Id, map => map.Generator(Generators.Guid)); rt.Property(x => x.Name); rt.Set(x => x.Users, map => { map.Table("UsersToRoles"); map.Key(km => km.Column("RoleId")); }, rel => rel.ManyToMany(mm => { mm.Column("UserId"); mm.ForeignKey("FK_UserInRole"); })); }); var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); return mappings; }
public void CreateSqlSchema() { var sqlBuilder = new SqlConnectionStringBuilder(); sqlBuilder.DataSource = "(local)"; sqlBuilder.InitialCatalog = "nservicebus"; sqlBuilder.IntegratedSecurity = true; var cfg = new Configuration() .DataBaseIntegration(x => { x.Dialect<MsSql2008Dialect>(); x.ConnectionString = sqlBuilder.ConnectionString; }); var mapper = new ModelMapper(); mapper.AddMappings(typeof(NHibernate.Config.SubscriptionMap).Assembly.GetExportedTypes()); HbmMapping faultMappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); cfg.AddMapping(faultMappings); File.WriteAllText("schema.sql", ""); new SchemaExport(cfg).Create(x => File.AppendAllText("schema.sql", x), true); subscriptionStorageSessionProvider = new SubscriptionStorageSessionProvider(cfg.BuildSessionFactory()); storage = new SubscriptionStorage(subscriptionStorageSessionProvider); }
protected override HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class<Document>(rc => { rc.Id(x => x.Id, idMapper => idMapper.Generator(Generators.Identity)); rc.ManyToOne(x => x.Blob, m => { m.Cascade(Mapping.ByCode.Cascade.All); }); rc.Property(x => x.Name); }); mapper.Class<Blob>(map => { map.Id(x => x.Id, idMapper => idMapper.Generator(Generators.Identity)); map.Property(x => x.Bytes, y => { y.Column(x => { x.SqlType("varbinary(max)"); x.Length(int.MaxValue); }); y.Lazy(true); }); }); return mapper.CompileMappingForAllExplicitlyAddedEntities(); }
public void Setup() { var mapper = new ModelMapper(); mapper.AddMapping<OutboxEntityMap>(); var configuration = new global::NHibernate.Cfg.Configuration() .AddProperties(new Dictionary<string, string> { { "dialect", dialect }, { global::NHibernate.Cfg.Environment.ConnectionString,connectionString } }); configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); new SchemaUpdate(configuration).Execute(false, true); SessionFactory = configuration.BuildSessionFactory(); Session = SessionFactory.OpenSession(); persister = new OutboxPersister { StorageSessionProvider = new FakeSessionProvider(SessionFactory, Session), EndpointName = "TestEndpoint" }; }
protected override HbmMapping GetMappings() { // The impl/mapping of the bidirectional one-to-many sucks but was provided as is var mapper = new ModelMapper(); mapper.BeforeMapClass += (i, t, cm) => cm.Id(map => { map.Column((t.Name + "Id").ToUpperInvariant()); map.Generator(Generators.HighLow, g => g.Params(new { max_lo = "1000" })); }); mapper.Class<Customer>(ca => { ca.Lazy(false); ca.Id(x => x.Id, m => { }); ca.NaturalId(x => x.Property(c => c.Name, p => p.NotNullable(true))); ca.Property(x => x.Address, p => p.Lazy(true)); ca.Set(c => c.Orders, c => { c.Key(x => x.Column("CUSTOMERID")); c.Inverse(true); c.Cascade(Mapping.ByCode.Cascade.All); }, c => c.OneToMany()); }); mapper.Class<Order>(cm => { cm.Id(x => x.Id, m => { }); cm.Property(x => x.Date); cm.ManyToOne(x => x.Customer, map => map.Column("CUSTOMERID")); }); return mapper.CompileMappingForAllExplicitlyAddedEntities(); }
protected override HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class<Employee>(mc => { mc.Id(x => x.Id, map => { map.Generator(Generators.Identity); map.Column("Id"); }); mc.ManyToOne<EmployeeInfo>(x => x.Info, map => { map.Column("Info_id"); map.Unique(true); map.Cascade(Mapping.ByCode.Cascade.All | Mapping.ByCode.Cascade.DeleteOrphans); }); }); mapper.Class<EmployeeInfo>(cm => { cm.Id(x => x.Id, m => { m.Generator(Generators.Identity); m.Column("Id"); }); cm.OneToOne<Employee>(x => x.EmployeeDetails, map => { map.PropertyReference(x => x.Info); }); }); return mapper.CompileMappingForAllExplicitlyAddedEntities(); }
protected override HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class<Parent>(rc => { rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb)); rc.Property(x => x.Name); rc.List(x => x.Children, m => { m.Lazy(CollectionLazy.Extra); m.Cascade(Mapping.ByCode.Cascade.All | Mapping.ByCode.Cascade.DeleteOrphans); m.Inverse(true); }, relation => relation.OneToMany()); }); mapper.Class<Child>(rc => { rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb)); rc.Property(x => x.Name); rc.ManyToOne(x => x.Parent); }); return mapper.CompileMappingForAllExplicitlyAddedEntities(); }
public void ShouldProperlyMapComponentWhenMappingOnlyPartOfItInSomePlaces() { var mapper = new ModelMapper(); mapper.Class<ClassWithComponents>(cm => { cm.Component(x => x.Component1, c => { c.Property(x => x.PropertyOne, p => p.Column("OnePropertyOne")); }); cm.Component(x => x.Component2, c => { c.Property(x => x.PropertyOne, p => p.Column("TwoPropertyOne")); c.Property(x => x.PropertyTwo, p => p.Column("TwoPropertyTwo")); }); }); //Compile, and get the component property in which we mapped only one inner property var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); var component1PropertyMapping = (HbmComponent)mappings.RootClasses[0].Properties.Single(x => x.Name == "Component1"); //There should be only one inner property in the mapping of this component // Note: take a look at how CURRENTLY the test fails with 1 expected vs 2, instead of vs 3. // This means that the "PropertyThree" property of the component that was never mapped, is not taken into account (which is fine). Assert.That(component1PropertyMapping.Items.Length, Is.EqualTo(1)); }
public static HbmMapping GetMapping() { var modelMapper = new ModelMapper(); modelMapper.AddMappings(Assembly.GetAssembly(typeof(PeopleMap)).GetExportedTypes()); HbmMapping mapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities(); return mapping; }
protected override HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class <EntityComplex>( rc => { rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb)); rc.Version(ep => ep.Version, vm => { }); rc.Property(x => x.Name); rc.Property(ep => ep.LazyProp, m => m.Lazy(true)); rc.ManyToOne(ep => ep.Child1, m => m.Column("Child1Id")); rc.ManyToOne(ep => ep.Child2, m => m.Column("Child2Id")); rc.ManyToOne(ep => ep.SameTypeChild, m => m.Column("SameTypeChildId")); rc.Bag( ep => ep.ChildrenList, m => { m.Cascade(Mapping.ByCode.Cascade.All); m.Inverse(true); }, a => a.OneToMany()); }); mapper.Class <EntitySimpleChild>( rc => { rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb)); rc.Property(x => x.Name); }); mapper.Class <EntityWithCompositeId>( rc => { rc.ComponentAsId( e => e.Key, ekm => { ekm.Property(ek => ek.Id1); ekm.Property(ek => ek.Id2); }); rc.Property(e => e.Name); }); return(mapper.CompileMappingForAllExplicitlyAddedEntities()); }
public void CompileMappingForDynamicInMemoryAssembly() { const int assemblyGenerateCount = 10; var code = GenerateCode(assemblyGenerateCount); var assembly = CompileAssembly(code); var config = TestConfigurationHelper.GetDefaultConfiguration(); var mapper = new ModelMapper(); mapper.AddMappings(assembly.GetExportedTypes()); config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); Assert.That(config.ClassMappings, Has.Count.EqualTo(assemblyGenerateCount), "Not all virtual assembly mapped"); // Ascertain the mappings are usable. using (var sf = config.BuildSessionFactory()) { var se = new SchemaExport(config); se.Create(false, true); try { using (var s = sf.OpenSession()) using (var tx = s.BeginTransaction()) { foreach (var entityClass in assembly.GetExportedTypes() .Where(t => !typeof(IConformistHoldersProvider).IsAssignableFrom(t))) { var ctor = entityClass.GetConstructor(Array.Empty <System.Type>()); Assert.That(ctor, Is.Not.Null, $"Default constructor for {entityClass} not found"); var entity = ctor.Invoke(Array.Empty <object>()); s.Save(entity); } tx.Commit(); } using (var s = sf.OpenSession()) using (var tx = s.BeginTransaction()) { var entities = s.CreateQuery("from System.Object").List <object>(); Assert.That(entities, Has.Count.EqualTo(assemblyGenerateCount), "Not all expected entities were persisted"); tx.Commit(); } } finally { TestCase.DropSchema(false, se, (ISessionFactoryImplementor)sf); } } }
static void Main() { Configuration hibernateConfig = new Configuration(); hibernateConfig.DataBaseIntegration(x => { x.ConnectionStringName = "NServiceBus/Persistence"; x.Dialect <MsSql2012Dialect>(); }); #region NHibernate hibernateConfig.SetProperty("default_schema", "receiver"); #endregion ModelMapper mapper = new ModelMapper(); mapper.AddMapping <OrderMap>(); hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); new SchemaExport(hibernateConfig).Execute(false, true, false); #region ReceiverConfiguration BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.UseTransport <SqlServerTransport>() .DefaultSchema("receiver") .UseSpecificConnectionInformation(endpoint => { if (endpoint == "error") { return(ConnectionInfo.Create().UseSchema("dbo")); } if (endpoint == "audit") { return(ConnectionInfo.Create().UseSchema("dbo")); } string schema = endpoint.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant(); return(ConnectionInfo.Create().UseSchema(schema)); }); busConfiguration.UsePersistence <NHibernatePersistence>() .UseConfiguration(hibernateConfig) .RegisterManagedSessionInTheContainer(); #endregion using (Bus.Create(busConfiguration).Start()) { Console.WriteLine("Press <enter> to exit"); Console.ReadLine(); } }
public void ExportSchema() { // Inicio do Setup do NH var config = new Configuration(); config.DataBaseIntegration( db => { db.Dialect <MsSql2008Dialect>(); db.ConnectionStringName = "DefaultNH"; db.SchemaAction = SchemaAutoAction.Recreate; }); ModelMapper modelMapper = new ModelMapper(); modelMapper.AddMapping <ProdutoNHMap>(); modelMapper.AddMapping <DepartamentoNHMap>(); config.AddDeserializedMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities(), "Domain"); ISessionFactory sessionFactory = config.BuildSessionFactory(); // Fim do Setup do NH - Isso deve ficar no start da app (Global.asax por exemplo) using (var session = sessionFactory.OpenSession()) { // Criteria API // HQL // Linq var produtosAcima1000 = session.QueryOver <Produto>().List(); foreach (var produto in produtosAcima1000) { Console.WriteLine(produto); } } using (var session = sessionFactory.OpenSession()) { var produto = new Produto(); produto.Nome = "Teste #1"; produto.Preco = 90; produto.Quantidade = 123; produto.Ativo = true; session.Save(produto); session.Flush(); } }
public static void Configure() { var config = new Configuration(); config.Configure(); var mapper = new ModelMapper(); mapper.AddMapping <UserMap>(); config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); _sessionFactory = config.BuildSessionFactory(); }
protected override HbmMapping GetMappings() { var mapper = new ModelMapper(); // Note: DeleteOrphans has no sense, only added to match the case reported. mapper.Class <Cat>(cm => { cm.Id(x => x.Id, map => map.Generator(Generators.Identity)); cm.Bag(x => x.Children, map => map.Cascade(Mapping.ByCode.Cascade.All.Include(Mapping.ByCode.Cascade.DeleteOrphans)), rel => rel.OneToMany()); }); var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); return(mappings); }
public void CanSpecifyUnsavedValue() { //NH-3048 var mapper = new ModelMapper(); mapper.Class <MyClass>(map => map.ComponentAsId(x => x.Id, x => { x.UnsavedValue(UnsavedValueType.Any); })); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); Assert.AreEqual(mapping.RootClasses[0].CompositeId.unsavedvalue, HbmUnsavedValueType.Any); }
private HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class <MyRelated>(rm => rm.Id(x => x.Id)); mapper.Class <MyEntity>(rm => { rm.Id(x => x.Id); rm.Bag(x => x.Relateds, am => am.Persister <MyCollectionPersister>(), rel => rel.OneToMany()); }); var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); return(mappings); }
public void Start() { _host = WebApp.Start <Startup>(Endpoint); Console.WriteLine(); Console.WriteLine("Hangfire Server started."); Console.WriteLine("Dashboard is available at {0}/hangfire", Endpoint); Console.WriteLine(); var config = new NHibernate.Cfg.Configuration(); config.DataBaseIntegration(db => { db.Dialect <MsSql2008Dialect>(); db.ConnectionStringName = "DataContext"; }); var mapper = new ModelMapper(); mapper.AddMapping <ApplicationMap>(); mapper.AddMapping <EnviromentMap>(); mapper.AddMapping <DeployTaskMap>(); mapper.AddMapping <ParameterMap>(); mapper.AddMapping <DeploymentMap>(); mapper.AddMapping <ApplicationAdministratorsMap>(); mapper.AddMapping <AllowedGroupMap>(); mapper.AddMapping <AllowedUserMap>(); mapper.AddMapping <LogEntryMap>(); mapper.AddMapping <MailTaskMap>(); mapper.AddMapping <LocalScriptTaskMap>(); mapper.AddMapping <RemoteScriptTaskMap>(); mapper.AddMapping <DatabaseTaskMap>(); mapper.AddMapping <AgentMap>(); mapper.AddMapping <ApplicationGroupMap>(); mapper.AddMapping <DeploymentTaskMap>(); mapper.AddMapping <TaskTemplateMap>(); mapper.AddMapping <TaskTemplateVersionMap>(); mapper.AddMapping <TaskTemplateParameterMap>(); mapper.AddMapping <TemplatedTaskMap>(); mapper.AddMapping <TemplatedTaskParameterMap>(); mapper.AddMapping <MaintenanceTaskMap>(); mapper.AddMapping <MaintenanceLogEntryMap>(); config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); DeployJob.Store = config.BuildSessionFactory(); LogsCompactionJob.Store = DeployJob.Store; MaintenanceJob.Store = DeployJob.Store; HealthCheckJob.Store = DeployJob.Store; }
private static HbmMapping CreateMapping() { var mapper = new ModelMapper(); //Add the person mapping to the model mapper mapper.AddMappings(new List <System.Type> { typeof(QuoteMap), typeof(InstrumentMap) }); //Create and return a HbmMapping of the model mapping in code return(mapper.CompileMappingForAllExplicitlyAddedEntities()); }
public void ConfigureHibernateMapping() { NHibernate.Cfg.Configuration hibernateConfig = (UnitOfWork.UnitOfWorkFactory as NHibernateUnitOfWorkFactory).Configuration; var mapper = new ModelMapper(); mapper.AddMappings(typeof(ProductModelMap).Assembly.GetExportedTypes()); mapper.AddMappings(typeof(DistributorModelMap).Assembly.GetExportedTypes()); mapper.AddMappings(typeof(QrCodeModelMap).Assembly.GetExportedTypes()); hibernateConfig.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), "FertilizerPlantScheme"); SchemaUpdate schema = new SchemaUpdate(hibernateConfig); schema.Execute(true, true); }
public HbmMapping Map() { MapPerson(); MapInfo(); MapFoodPreference(); MapCompany(); MapContact(); MapMenuItem(); MapLodging(); MapLodgingType(); MapLoadings(); return(_modelMapper.CompileMappingForAllExplicitlyAddedEntities()); }
protected override HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class <Image>(rc => { rc.Cache(map => map.Usage(CacheUsage.NonstrictReadWrite)); rc.Id(x => x.Id); rc.Property(x => x.Data, map => map.Lazy(true)); }); var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); return(mappings); }
protected override Cfg.MappingSchema.HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class <Entity>(ca => { ca.Lazy(false); ca.Id(x => x.Id, map => map.Generator(Generators.GuidComb)); ca.Property(x => x.EnglishName); ca.Property(x => x.GermanName); }); return(mapper.CompileMappingForAllExplicitlyAddedEntities()); }
Configuration CreateConfiguration() { ModelMapper mapper = CreateModelMapper(); HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); var configuration = new Configuration(); configuration = ApplyDatabaseIntegration(configuration); configuration.AddMapping(domainMapping); return(configuration); }
protected override void AddMappings(Configuration configuration) { var modelMapper = new ModelMapper(); modelMapper.Class <Entity>( x => { x.Id(e => e.Id); x.Property(e => e.Name); x.Table(nameof(Entity)); }); configuration.AddMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities()); }
protected override void Configure(Configuration cfg) { var mapper = new ModelMapper(); mapper.AddMapping <ProductMapping>(); mapper.AddMapping <MovieMapping>(); mapper.AddMapping <BookMapping>(); mapper.AddMapping <ActorRoleMapping>(); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); cfg.AddMapping(mapping); }
protected override HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class <Animal>(rc => { rc.Id(x => x.Id, m => m.Generator(Generators.Assigned)); rc.Property(x => x.Weight); }); mapper.UnionSubclass <Cat>(x => x.Property(p => p.NumberOfLegs)); return(mapper.CompileMappingForAllExplicitlyAddedEntities()); }
protected override HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class <Entity>( rc => { rc.Cache(m => m.Usage(CacheUsage.NonstrictReadWrite)); rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb)); rc.Property(x => x.Name); }); return(mapper.CompileMappingForAllExplicitlyAddedEntities()); }
private static Configuration CreateConfiguration() { var configuration = new Configuration(); configuration.Configure("hibernate.sqlite.config"); var mapper = new ModelMapper(); mapper.AddMapping <AuthorMappingSqlite>(); mapper.AddMapping <BookMappingSqlite>(); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); configuration.AddMapping(mapping); return(configuration); }
protected override HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class <Entity>( rc => { rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb)); rc.Property(x => x.Name); rc.Property(x => x.LazyProp, m => m.Lazy(true)); }); return(mapper.CompileMappingForAllExplicitlyAddedEntities()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "NH.Example.Web", Version = "v1" }); }); services.AddSingleton <ISessionFactory>(serviceProvider => { var configuration = new Configuration(); configuration.DataBaseIntegration(db => { db.ConnectionString = "Data Source=NHExample.db"; db.Driver <SQLite20Driver>(); db.Dialect <SQLiteDialect>(); db.LogSqlInConsole = true; db.LogFormattedSql = true; }); var modelMapper = new ModelMapper(); modelMapper.AddMapping <UserMapping>(); modelMapper.AddMapping <RoleMapping>(); modelMapper.AddMapping <PhoneMapping>(); var mappings = modelMapper.CompileMappingForAllExplicitlyAddedEntities(); configuration.AddMapping(mappings); var sessionFactory = configuration.BuildSessionFactory(); var schemaUpdate = new SchemaUpdate(configuration); schemaUpdate.Execute(true, true); return(sessionFactory); }); services.AddScoped <ISession>(serviceProvider => { var sessionFactory = serviceProvider.GetService <ISessionFactory>(); var session = sessionFactory.OpenSession(); return(session); }); }
protected virtual void AddDefaultMapping(NHibernate.Cfg.Configuration cfg) { ModelMapper mm = new ModelMapper(); mm.Class <ContentItem>(ContentItemCustomization); mm.Class <ContentDetail>(ContentDetailCustomization); mm.Class <DetailCollection>(DetailCollectionCustomization); mm.Class <AuthorizedRole>(AuthorizedRoleCustomization); mm.Class <ContentVersion>(ContentVersionCustomization); var compiledMapping = mm.CompileMappingForAllExplicitlyAddedEntities(); cfg.AddDeserializedMapping(compiledMapping, "N2"); }
protected override HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class <StringClass>(ca => { ca.Lazy(false); ca.Id(x => x.Id, map => map.Generator(Generators.Assigned)); ca.Property(x => x.StringValue, map => map.Length(10)); ca.Property(x => x.LongStringValue, map => map.Length(GetLongStringMappedLength())); }); return(mapper.CompileMappingForAllExplicitlyAddedEntities()); }
/// <summary> /// 为事件订阅者信息与要保存的表建立NHibernate映射 /// </summary> public static Configuration AddSubscriptionNHibernateMappings(this Configuration configuration) { var nhibernateConfiguration = ObjectContainer.Resolve <NHibernateCfg.Configuration>(); var subscriptionTable = nhibernateConfiguration.Properties["subscriptionTable"]; if (!string.IsNullOrEmpty(subscriptionTable)) { var mapper = new ModelMapper(); var mapping = Activator.CreateInstance(typeof(SubscriptionMapping), subscriptionTable) as IConformistHoldersProvider; mapper.AddMapping(mapping); nhibernateConfiguration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); } return(configuration); }
public static void Configure() { var Wconfig = new Configuration(); Wconfig.Configure(); var mapper = new ModelMapper(); mapper.AddMapping <DerslerMap>(); mapper.AddMapping <KisilerMap>(); mapper.AddMapping <YetkiMap>(); mapper.AddMapping <KisilerDerslerMap>(); Wconfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); _sessionfactory = Wconfig.BuildSessionFactory(); }
public InMemoryDatabaseConfiguration() { this.DataBaseIntegration(db => { db.ConnectionReleaseMode = ConnectionReleaseMode.OnClose; //db.Dialect<SQLiteDialect>(); //db.Driver<SQLite20Driver>(); //db.ConnectionString = "data source=:memory"; db.LogSqlInConsole = true; db.LogFormattedSql = true; db.BatchSize = 20; db.Timeout = 30; }); SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName); SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName); SetProperty(Environment.ConnectionString, "data source=:memory:"); this.Cache(cache => { cache.UseQueryCache = true; //cache.QueryCache<StandardQueryCache>(); cache.Provider <HashtableCacheProvider>(); }); this.CurrentSessionContext <ThreadLocalSessionContext>(); var modelMapper = new ModelMapper(); modelMapper.AddMapping <EmployeeMappings>(); modelMapper.AddMapping <AddressMappings>(); modelMapper.AddMapping <BenefitMappings>(); modelMapper.AddMapping <LeaveMappings>(); modelMapper.AddMapping <SkillsEnhancementAllowanceMappings>(); modelMapper.AddMapping <SeasonTicketLoanMappings>(); modelMapper.AddMapping <CommunityMappings>(); AddMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities()); var sessionFactory = BuildSessionFactory(); session = sessionFactory.OpenSession(); using (var tx = session.BeginTransaction()) { new SchemaExport(this).Execute(true, true, false, session.Connection, Console.Out); tx.Commit(); } session.Clear(); }
public void TestMapComponentEntity() { var mapper = new ModelMapper(); mapper.Class <ClassWithMapComponentEntity>( c => { c.Lazy(false); c.Id(id => id.Id, id => id.Generator(Generators.Identity)); c.Map( m => m.Map, col => { col.Table("component_entity"); col.Key(k => k.Column("id")); }, key => key.Component( cmp => { cmp.Property(p => p.A); cmp.Property(p => p.B); }), element => element.ManyToMany(e => e.Column("element"))); }); mapper.Component <Component>( c => { c.Property(p => p.A); c.Property(p => p.B); }); mapper.Class <Entity>( c => { c.Lazy(false); c.Id(id => id.A, id => id.Generator(Generators.Identity)); c.Property(p => p.B); }); var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); var hbmClass = mappings.RootClasses.FirstOrDefault(c => c.Name == typeof(ClassWithMapComponentEntity).Name); var hbmMap = hbmClass.Properties.OfType <HbmMap>().SingleOrDefault(); Assert.That(hbmMap, Is.Not.Null); Assert.That(hbmMap.Item, Is.TypeOf <HbmCompositeMapKey>()); Assert.That(hbmMap.Item1, Is.TypeOf <HbmManyToMany>()); }
private static void InitNHibernate() { if (_sessionFactory == null) { lock (LockObject) { // Создание NHibernate-конфигурации приложения на основании описаний из web.config. // После этого вызова, в том числе, из сборки будут извлечены настройки маппинга, // заданные в xml-файлах. var configure = new Configuration().Configure(); // Настройка маппинга, созданного при помощи mapping-by-code var mapper = new ModelMapper(); mapper.AddMappings(new List <Type> { // Перечень классов, описывающих маппинг typeof(AttributeMap), typeof(EssenceMap), typeof(EssenceAttributeValueMap), typeof(EssenceTypeMap), typeof(EssenceTypeAttributeMap), typeof(ObjectStatusMap), typeof(ReferenceTypeMap), typeof(ReferenceMap), typeof(EssenceTypeReferenceTypeMap), typeof(EssenceTypeGroupMap), typeof(RoleMap), typeof(ManagerMap), typeof(ManagerBaseMap), typeof(RoleAccessMap), typeof(RoleAccessLightMap), typeof(ManagerAccessMap), typeof(ManagerAccessLightMap), }); // Добавление маппинга, созданного при помощи mapping-by-code, // в NHibernate-конфигурацию приложения configure.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), null); //configure.LinqToHqlGeneratorsRegistry<CompareValuesGeneratorsRegistry>(); //configure.LinqToHqlGeneratorsRegistry<InGeneratorRegistry>(); configure.DataBaseIntegration(x => { x.LogSqlInConsole = true; x.LogFormattedSql = true; }); _sessionFactory = configure.BuildSessionFactory(); } } }
public static async Task Main(string[] args) { var builder = new HostBuilder() .ConfigureAppConfiguration((hostingContext, config) => { config.AddJsonFile("appsettings.json", optional: false); config.AddEnvironmentVariables(); if (args != null) { config.AddCommandLine(args); } }) .ConfigureServices((hostContext, services) => { services.AddOptions(); services.AddSingleton <IHostedService, NhibernateService>(); var config = new Configuration(); config.SetProperty(NHibernate.Cfg.Environment.ShowSql, "true"); config.DataBaseIntegration(db => { db.ConnectionString = hostContext.Configuration["ConnectionStrings:DefaultConnection"]; db.Dialect <MsSql2012Dialect>(); db.Driver <SqlClientDriver>(); }); var mapping = new ModelMapper(); mapping.AddMapping <CustomerConfiguration>(); mapping.AddMapping <SiteConfiguration>(); var hbmMapping = mapping.CompileMappingForAllExplicitlyAddedEntities(); config.AddDeserializedMapping(hbmMapping, "dbo"); var dialect = Dialect.GetDialect(config.GetDerivedProperties()); SchemaMetadataUpdater.QuoteTableAndColumns(config, dialect); SchemaValidator sv = new SchemaValidator(config); sv.Validate(); config.SetListener(ListenerType.PostInsert, new ExamplePostInsertEventListener()); config.SetListener(ListenerType.PostUpdate, new ExamplePostUpdateEventListener()); config.SetListener(ListenerType.PostDelete, new ExamplePostDeleteEventListener()); var sessionFactory = config.BuildSessionFactory(); services.TryAddSingleton <ISessionFactory>(sessionFactory); }) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); }); await builder.RunConsoleAsync(); }