public virtual void MapTypes(List <Type> allTypes, NHibernate.Cfg.Configuration cfg, Func <string, string> formatter) { var m = new HbmMapping(); m.Items = allTypes.Select(t => { var sc = new HbmSubclass(); sc.name = GetName(t); sc.extends = GetName(t.BaseType); sc.discriminatorvalue = map.GetOrCreateDefinition(t).Discriminator ?? t.Name; sc.lazy = false; sc.lazySpecified = true; var propertyMappings = GetPersistables(t) .Select(p => p.Attribute.GetPropertyMapping(p.DeclaringProperty, formatter)) .ToList(); if (propertyMappings.Count > 0) { if (sc.Items == null) { sc.Items = propertyMappings.ToArray(); } else { sc.Items = sc.Items.Union(propertyMappings).ToArray(); } } return(sc); }).ToArray(); var dbg = m.AsString(); cfg.AddDeserializedMapping(m, "N2"); }
public static IDictionary<string, ISessionFactory> BuildSessionFactory() { // var configure = new Configuration(); var mapping = GetMappings(); //configure.Configure(); //configure.AddDeserializedMapping(mapping, "NHSchema"); if (!CommonHelper.AllowMultiTenancy(out _ConnectionStringName)) { var config = new Configuration(); // config.SetInterceptor(new NHSQLInterceptor()); config.Configure(); var _host = EngineContext.Current.Resolve<HttpContextBase>().Request.Url.Authority; config.AddDeserializedMapping(mapping, "NHSchema"); config.Configure() .SetProperty(NHibernate.Cfg.Environment.ConnectionStringName, _ConnectionStringName) . SetProperty(NHibernate.Cfg.Environment.ShowSql, "true") .SetProperty(NHibernate.Cfg.Environment.BatchSize, "0") .SetProperty(NHibernate.Cfg.Environment.CacheRegionPrefix, _host); if (!_allFactories.ContainsKey(_host)) _allFactories.Add(_host, config.BuildSessionFactory()); } else { XmlNodeList nodes = ConfigurationFile.GetElementsByTagName("Tenant"); foreach (XmlNode n in nodes) { var config = new Configuration(); // config.SetInterceptor(new NHSQLInterceptor()); config.Configure(); config.AddDeserializedMapping(mapping, "NHSchema"); config.Configure() .SetProperty(NHibernate.Cfg.Environment.ConnectionString, n["ConnectionString"].InnerText) . SetProperty(NHibernate.Cfg.Environment.ShowSql, "true") .SetProperty(NHibernate.Cfg.Environment.BatchSize, "0") .SetProperty(NHibernate.Cfg.Environment.CacheRegionPrefix, n["HostName"].InnerText); // config.SetInterceptor(new NHSQLInterceptor()); if (!_allFactories.ContainsKey(n["HostName"].InnerText)) _allFactories.Add(n["HostName"].InnerText, config.BuildSessionFactory()); } } return _allFactories; }
public override void AlterConfiguration(NHibernate.Cfg.Configuration cfg) { ModelMapper mm = new ModelMapper(); mm.Class <FileSystemItem>(FileSystemItemCustomization); mm.Class <FileSystemChunk>(FileSystemChunkCustomization); var compiledMapping = mm.CompileMappingForAllExplicitlyAddedEntities(); cfg.AddDeserializedMapping(compiledMapping, "N2"); }
public override void AlterConfiguration(NHibernate.Cfg.Configuration cfg) { ModelMapper mm = new ModelMapper(); mm.Class <Bucket>(BucketCustomization); mm.Class <Statistic>(StatisticCustomization); var compiledMapping = mm.CompileMappingForAllExplicitlyAddedEntities(); cfg.AddDeserializedMapping(compiledMapping, "N2"); }
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); var compiledMapping = mm.CompileMappingForAllExplicitlyAddedEntities(); cfg.AddDeserializedMapping(compiledMapping, "N2"); }
private static ISessionFactory CreateSessionFactory() { var mapper = new ModelMapper(); mapper.AddMappings(Assembly.Load("MessageBoard.Domain").GetTypes()); HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); config = new NHibernate.Cfg.Configuration(); config.Configure(); config.AddDeserializedMapping(domainMapping,"domainMapping"); config.Properties[NHibernate.Cfg.Environment.CurrentSessionContextClass]="web"; config.SetProperty(NHibernate.Cfg.Environment.ShowSql, "true").SetProperty(NHibernate.Cfg.Environment.BatchSize, "100"); return config.BuildSessionFactory(); }
protected override void SetupConfiguration(NHibernate.Cfg.Configuration cfg) { base.SetupConfiguration(cfg); ModelMapper mapper = new ModelMapper(); // classes do estoque mapper.AddMapping <EmpenhoMapper>(); mapper.AddMapping <EmpenhoMvtoMapper>(); mapper.AddMapping <EventoMapper>(); mapper.AddMapping <EventoMvtoMapper>(); mapper.AddMapping <GestorMapper>(); mapper.AddMapping <ItemMapper>(); mapper.AddMapping <MensagemWsMapper>(); mapper.AddMapping <ParametrosMapper>(); mapper.AddMapping <ParamProgMapper>(); mapper.AddMapping <ProcessoFilaMapper>(); mapper.AddMapping <ProcessoMapper>(); mapper.AddMapping <ProgramaSaudeMapper>(); mapper.AddMapping <TpMotivoMapper>(); mapper.AddMapping <TpAcaoMapper>(); HbmMapping mapping = mapper.CompileMappingFor(new[] { // estoque typeof(Empenho), typeof(EmpenhoMvto), typeof(Evento), typeof(EventoMvto), typeof(Gestor), typeof(Item), typeof(MensagemWs), typeof(Parametros), typeof(ParamProg), typeof(ProcessoFila), typeof(Processo), typeof(ProgramaSaude), typeof(TpMotivo), typeof(TpAcao), }); cfg.AddDeserializedMapping(mapping, null); cfg.AddAssembly("Prodesp.Monitor.DAL"); }
/// <summary>Adds mappings to the configuration.</summary> /// <param name="cfg">The configuration to add the mappings to.</param> /// <param name="name">The resource name of the embedded resource.</param> protected virtual void AddMapping(NHibernate.Cfg.Configuration cfg, string name) { if (!string.IsNullOrEmpty(name)) { using (Stream stream = GetStreamFromName(name)) { if (stream == null) { throw new ArgumentException("Could not read stream from embedded resource '" + name + "'", "name"); } using (StreamReader reader = new StreamReader(stream)) { var mappingXml = reader.ReadToEnd(); mappingXml = FormatMapping(mappingXml); var xmlReader = new XmlTextReader(mappingXml, XmlNodeType.Document, null); var mappingDocument = cfg.LoadMappingDocument(xmlReader, "N2"); cfg.AddDeserializedMapping(mappingDocument.Document, mappingDocument.Name); } } } }
public virtual void MapTypes(List <Type> allTypes, NHibernate.Cfg.Configuration cfg, Func <string, string> formatter) { var m = new HbmMapping(); m.Items = allTypes.Select(t => { var sc = new HbmSubclass(); sc.name = GetName(t); sc.extends = GetName(t.BaseType); sc.discriminatorvalue = map.GetOrCreateDefinition(t).Discriminator ?? t.Name; sc.lazy = false; sc.lazySpecified = true; var propertyMappings = GetPersistables(t) .Select(p => p.Attribute.GetPropertyMapping(p.DeclaringProperty, formatter)) .ToList(); if (propertyMappings.Count > 0) { if (sc.Items == null) { sc.Items = propertyMappings.ToArray(); } else { sc.Items = sc.Items.Union(propertyMappings).ToArray(); } } logger.DebugFormat("Generating subclass {0} with discriminator {1} extending {2} with {3} items ({4} property mappings)", sc.name, sc.discriminatorvalue, sc.extends, sc.Items != null ? sc.Items.Length.ToString() : "(null)", propertyMappings.Count); return(sc); }).ToArray(); if (Debugger.IsAttached) { var dbg = m.AsString(); } cfg.AddDeserializedMapping(m, "N2"); }
public void Init(string connectionStringName = "local", bool debug = false, string database = "") { //ilmerge //если сборки объединены то логика определения системы протоколирование не работает //нужно вручную настроить ее LoggerProvider.SetLoggersFactory(new Log4NetLoggerFactory()); var mappingDialect = new MySQL5Dialect(); var mapper = new ConventionModelMapper(); var baseInspector = new SimpleModelInspector(); var simpleModelInspector = ((SimpleModelInspector)mapper.ModelInspector); simpleModelInspector.IsPersistentProperty((m, declared) => { return(((IModelInspector)baseInspector).IsPersistentProperty(m) && m.GetCustomAttributes(typeof(IgnoreAttribute), false).Length == 0); }); simpleModelInspector.IsRootEntity((type, declared) => { var modelInspector = ((IModelInspector)simpleModelInspector); return(declared || (type.IsClass && type.BaseType != null //если наследуемся от класса который не маплен то это простое наследование && (typeof(object) == type.BaseType || !modelInspector.IsEntity(type.BaseType)) || type.BaseType == typeof(BaseStatelessObject)) && modelInspector.IsEntity(type)); }); Index <Waybill>(w => w.WriteTime); Index <WaybillLine>(w => w.ProductId); Index <WaybillLine>(w => w.ProducerId); Index <WaybillLine>(w => w.Product); Index <WaybillLine>(w => w.SerialNumber); Index <WaybillLine>(w => w.RejectId); Index <WaybillLine>(w => w.EAN13); Index <Reject>(w => w.ProductId); Index <Reject>(w => w.ProducerId); Index <Reject>(w => w.Product); Index <Reject>(w => w.Series); Index <Offer>(o => o.ProductId); Index <Offer>(o => o.CatalogId); //индекс для восстановления заявок Index <Offer>(o => o.ProductSynonymId); Index <Offer>(o => o.PriceId); Index <Offer>(o => o.Id.RegionId); Index <SentOrder>(o => o.SentOn); Index <SentOrder>(o => o.ServerId); Index <DeletedOrder>(o => o.DeletedOn); Index <DeletedOrder>(o => o.ServerId); Index <MinCost>(r => r.Diff); Index <Catalog>(r => r.Name); Index <Drug>(r => r.EAN); Index <BarCode>(r => r.Value); Index <BarcodeProducts>(x => x.Barcode); mapper.Class <Drug>(x => x.Id(y => y.DrugId)); mapper.Class <Settings>(m => { m.Bag(o => o.Markups, c => { c.Inverse(true); c.Cascade(Cascade.DeleteOrphans | Cascade.All); }); m.Bag(o => o.PriceTags, c => { c.Inverse(true); c.Cascade(Cascade.DeleteOrphans | Cascade.All); }); m.Bag(o => o.Waybills, c => c.Cascade(Cascade.DeleteOrphans | Cascade.All)); m.Property(x => x.ClientTokenV2, c => c.Length(10000)); }); mapper.Class <MarkupConfig>(m => { m.Property(o => o.Begin, om => om.Access(Accessor.Field)); m.Property(o => o.End, om => om.Access(Accessor.Field)); }); mapper.Class <PriceTagSettings>(o => { o.Id(r => r.Id); }); mapper.Class <PriceTag>(m => { m.Bag(o => o.Items, c => { c.Inverse(true); c.Cascade(Cascade.DeleteOrphans | Cascade.All); }); }); mapper.Class <PriceTagItem>(o => { o.Id(r => r.Id); }); mapper.Class <MinOrderSumRule>(m => { m.ComposedId(c => { c.ManyToOne(p => p.Address); c.ManyToOne(p => p.Price, t => t.Columns(cm => cm.Name("PriceId"), cm => cm.Name("RegionId"))); }); m.Property(p => p.MinOrderSum); }); mapper.Class <Limit>(m => { m.ComposedId(c => { c.ManyToOne(p => p.Address); c.ManyToOne(p => p.Price, t => t.Columns(cm => cm.Name("PriceId"), cm => cm.Name("RegionId"))); }); m.Property(p => p.Value); }); mapper.Class <WaybillOrder>(m => { m.ComposedId(c => { c.Property(p => p.OrderLineId); c.Property(p => p.DocumentLineId); }); }); mapper.Class <Promotion>(m => { m.Bag(o => o.Catalogs, c => { c.Table("PromotionCatalogs"); c.Key(km => km.Column("PromotionId")); }, cm => { cm.ManyToMany(km => km.Column("CatalogId")); }); }); mapper.Class <ProducerPromotion>(m => { m.Bag(o => o.Catalogs, c => { c.Table("ProducerPromotionCatalogs"); c.Key(km => km.Column("PromotionId")); }, cm => { cm.ManyToMany(km => km.Column("CatalogId")); }); }); mapper.Class <ProducerPromotion>(m => { m.Bag(o => o.Suppliers, c => { c.Table("ProducerPromotionSuppliers"); c.Key(km => km.Column("PromotionId")); }, cm => { cm.ManyToMany(km => km.Column("SupplierId")); }); }); mapper.Class <Price>(m => { m.ComponentAsId(c => c.Id); m.Property(p => p.ContactInfo, c => c.Length(10000)); m.Property(p => p.OperativeInfo, c => c.Length(10000)); m.Property(p => p.RegionId, c => c.Insert(false)); m.Version(p => p.Timestamp, c => { c.Type(new TimestampType()); c.Column(cc => cc.Default("'0001-01-01 00:00:00'")); }); }); mapper.Class <Check>(m => { m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq")); }); mapper.Class <Mail>(m => { m.Property(p => p.Subject, c => c.Length(10000)); m.Property(p => p.Body, c => c.Length(10000)); }); mapper.Class <Order>(m => { m.Property(o => o.Frozen, om => om.Access(Accessor.Field)); m.ManyToOne(o => o.MinOrderSum, c => { c.Columns(cm => cm.Name("AddressId"), cm => cm.Name("PriceId"), cm => cm.Name("RegionId")); c.Insert(false); c.Update(false); }); m.ManyToOne(o => o.Limit, c => { c.Columns(cm => cm.Name("AddressId"), cm => cm.Name("PriceId"), cm => cm.Name("RegionId")); c.Insert(false); c.Update(false); }); m.Bag(o => o.Lines, c => { c.Cascade(Cascade.DeleteOrphans | Cascade.All); c.Inverse(true); }); }); mapper.Class <Waybill>(m => { //при миграции могут если поставщик отсутствует nhibernate будет перезаписывать m.ManyToOne(x => x.Address, x => x.Update(false)); m.ManyToOne(x => x.Supplier, x => x.Update(false)); m.Bag(o => o.Lines, c => { c.Cascade(Cascade.DeleteOrphans | Cascade.All); c.Inverse(true); }); }); mapper.Class <WaybillLine>(m => { m.Property(l => l.RetailCost, p => p.Access(Accessor.Field)); m.Property(l => l.RetailMarkup, p => p.Access(Accessor.Field)); m.Property(l => l.RealRetailMarkup, p => p.Access(Accessor.Field)); m.Property(l => l.MaxRetailMarkup, p => p.Access(Accessor.Field)); m.Bag(l => l.CertificateFiles, c => { c.Cascade(Cascade.DeleteOrphans | Cascade.All); }); }); mapper.Class <Address>(m => m.Bag(o => o.Orders, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); })); mapper.Class <InventoryDoc>(m => { m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq")); m.Bag(o => o.Lines, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); }); }); mapper.Class <InventoryLine>(m => { m.ManyToOne(x => x.Stock, p => p.Cascade(Cascade.Refresh)); }); mapper.Class <UnpackingDoc>(m => { m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq")); //m.Bag(o => o.Lines, c => { //c.Cascade(Cascade.All | Cascade.DeleteOrphans); //}); }); mapper.Class <UnpackingLine>(m => { m.ManyToOne(x => x.DstStock, p => p.Cascade(Cascade.All)); m.ManyToOne(x => x.SrcStock, p => p.Cascade(Cascade.All)); }); mapper.Class <WriteoffDoc>(m => { m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq")); m.Bag(o => o.Lines, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); }); }); mapper.Class <ReturnDoc>(m => { m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq")); m.Bag(o => o.Lines, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); }); }); mapper.Class <DisplacementDoc>(m => { m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq")); m.Bag(o => o.Lines, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); }); }); mapper.Class <DisplacementLine>(m => { m.ManyToOne(x => x.SrcStock, p => p.Cascade(Cascade.Refresh)); m.ManyToOne(x => x.DstStock, p => p.Cascade(Cascade.All)); }); mapper.Class <ReassessmentDoc>(m => { m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq")); m.Bag(o => o.Lines, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); }); }); mapper.Class <ReassessmentLine>(m => m.ManyToOne(x => x.DstStock, p => p.Cascade(Cascade.All))); mapper.Class <Offer>(m => { m.ManyToOne(o => o.Price, c => { c.Insert(false); c.Update(false); }); m.ManyToOne(o => o.LeaderPrice, c => c.Columns(cm => cm.Name("LeaderPriceId"), cm => cm.Name("LeaderRegionId"))); }); mapper.Class <OrderLine>(m => { m.Property(l => l.RetailMarkup, p => p.Access(Accessor.Field)); m.Property(l => l.RetailCost, p => p.Access(Accessor.Field)); }); mapper.Class <SentOrder>(m => { m.Bag(o => o.Lines, c => { c.Key(k => k.Column("OrderId")); c.Cascade(Cascade.DeleteOrphans | Cascade.All); c.Inverse(true); }); }); mapper.Class <DeletedOrder>(m => { m.Bag(o => o.Lines, c => { c.Key(k => k.Column("OrderId")); c.Cascade(Cascade.DeleteOrphans | Cascade.All); c.Inverse(true); }); }); mapper.Class <Mail>(m => { m.Bag(o => o.Attachments, c => { c.Cascade(Cascade.DeleteOrphans | Cascade.All); }); }); mapper.Class <BatchLine>(m => { m.Property(l => l.Comment, c => c.Length(10000)); m.Property(l => l.ServiceFields, c => c.Length(10000)); }); mapper.Class <AwaitedItem>(i => { i.ManyToOne(l => l.Catalog, c => c.Index("Catalog")); i.ManyToOne(l => l.Producer, c => c.Index("Producer")); }); mapper.Class <Stock>(m => { m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq")); m.Property(x => x.RetailCost, p => p.Access(Accessor.Field)); m.Property(x => x.RetailMarkup, p => p.Access(Accessor.Field)); }); mapper.BeforeMapClass += (inspector, type, customizer) => { customizer.Id(m => m.Generator(Generators.Native)); if (type == typeof(RegulatorRegistry)) { customizer.Table("RegulatorRegistry"); } }; mapper.BeforeMapProperty += (inspector, member, customizer) => { var propertyInfo = ((PropertyInfo)member.LocalMember); var propertyType = propertyInfo.PropertyType; if (member.GetContainerEntity(inspector) == typeof(ProductDescription)) { if (propertyType == typeof(string)) { customizer.Length(10000); } } if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?)) { customizer.Type <UtcToLocalDateTimeType>(); } if (propertyType.IsValueType && !propertyType.IsNullable()) { customizer.Column(c => c.Default(GetDefaultValue(propertyInfo, mappingDialect))); customizer.NotNullable(true); } if (indexes.Any(m => m.MetadataToken == propertyInfo.MetadataToken && m.Module == propertyInfo.Module)) { customizer.Index(propertyInfo.Name); } }; mapper.BeforeMapManyToMany += (inspector, member, customizer) => { //myisam не поддерживает внешние ключи customizer.ForeignKey("none"); }; mapper.BeforeMapBag += (inspector, member, customizer) => { customizer.Key(k => { k.Column(member.GetContainerEntity(inspector).Name + "Id"); //myisam не поддерживает внешние ключи k.ForeignKey("none"); }); }; mapper.BeforeMapManyToOne += (inspector, member, customizer) => { var propertyInfo = ((PropertyInfo)member.LocalMember); if (propertyInfo.PropertyType == typeof(Price)) { customizer.Columns(cm => cm.Name("PriceId"), cm => cm.Name("RegionId")); } else { customizer.Column(member.LocalMember.Name + "Id"); if (indexes.Contains(propertyInfo)) { customizer.Column(m => m.Index(member.LocalMember.Name + "Id")); } } customizer.NotFound(NotFoundMode.Ignore); //myisam не поддерживает внешние ключи customizer.ForeignKey("none"); }; var assembly = typeof(Offer).Assembly; var types = assembly.GetTypes() .Where(t => t.Namespace != null && t.Namespace.StartsWith("AnalitF.Net.Client.Models")) .Where(t => !t.IsAbstract && !t.IsInterface && t.GetProperty("Id") != null || t == typeof(MinOrderSumRule) || t == typeof(WaybillOrder) || t == typeof(Limit) || t == typeof(Drug)); var mapping = mapper.CompileMappingFor(types); PatchComponentColumnName(mapping); MappingHash = mapping.AsString().GetHashCode(); if (debug) { Console.WriteLine("MappingHash = {0}", MappingHash); Console.WriteLine(mapping.AsString()); } var connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; var driver = "NHibernate.Driver.MySqlDataDriver"; var dialect = typeof(DevartMySqlDialect).AssemblyQualifiedName; if (connectionString.Contains("Embedded=True")) { connectionString = FixRelativePaths(connectionString, database); driver = typeof(DevartDriver).AssemblyQualifiedName; } Configuration = new Configuration(); Configuration.AddProperties(new Dictionary <string, string> { { Environment.Dialect, dialect }, { Environment.ConnectionDriver, driver }, { Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider" }, { Environment.ConnectionString, connectionString }, { Environment.Hbm2ddlKeyWords, "none" }, #if DEBUG //если нужно отладить запросы хибера //для запросов в AddAwaited падает //{Environment.FormatSql, "true"}, #endif { Environment.ProxyFactoryFactoryClass, typeof(ProxyFactoryFactory).AssemblyQualifiedName }, }); Configuration.SetNamingStrategy(new PluralizeNamingStrategy()); Configuration.AddDeserializedMapping(mapping, assembly.GetName().Name); Factory = Configuration.BuildSessionFactory(); }
public override NHibernate.Cfg.Configuration Map(NHibernate.Cfg.Configuration cfg) { ModelMapper mapper = new ModelMapper(); mapper.Class <Address>(ca => { ca.Table("address"); ca.Lazy(true); ca.Id(x => x.CustomerId, map => { map.Column("customer_id"); map.Generator(Generators.Foreign <Address>(x => x.Customer)); }); ca.Property(x => x.City, x => { x.NotNullable(true); x.Column("city"); x.Length(50); }); ca.Property(x => x.Country, x => { x.NotNullable(true); x.Column("country"); x.Length(50); }); ca.Property(x => x.Street, x => { x.NotNullable(true); x.Column("street"); x.Length(50); }); ca.Property(x => x.ZipCode, x => { x.NotNullable(true); x.Column("zipcode"); x.Length(10); }); ca.OneToOne(x => x.Customer, x => { x.Constrained(true); }); }); mapper.Class <Customer>(ca => { ca.Table("customer"); ca.Lazy(true); ca.Id(x => x.CustomerId, map => { map.Column("customer_id"); map.Generator(Generators.HighLow); }); ca.NaturalId(x => x.Property(c => c.Name, y => { y.Column("name"); y.Length(50); y.NotNullable(true); })); ca.NaturalId(x => x.Property(c => c.Email, y => { y.Column("email"); y.Length(50); })); ca.Property(x => x.Name, p => { p.NotNullable(true); p.Column("name"); }); ca.Set(c => c.Orders, c => { c.Key(x => x.Column("customer_id")); c.Fetch(CollectionFetchMode.Select); c.Inverse(true); c.Lazy(CollectionLazy.Extra); c.Cascade(Cascade.All | Cascade.DeleteOrphans); }, c => c.OneToMany()); ca.Set(c => c.RecentOrders, c => { c.Key(x => x.Column("customer_id")); c.Fetch(CollectionFetchMode.Select); c.Where("(date >= (GETDATE() - 7))"); c.Inverse(true); c.Mutable(false); c.Cascade(Cascade.None); c.Lazy(CollectionLazy.Lazy); }, c => c.OneToMany()); ca.OneToOne(x => x.Address, x => { x.Cascade(Cascade.All | Cascade.DeleteOrphans); x.Constrained(false); }); }); mapper.Class <Order>(ca => { ca.Table("order"); ca.Lazy(true); ca.Id(x => x.OrderId, map => { map.Column("order_id"); map.Generator(Generators.HighLow); }); ca.Property(x => x.State, x => { x.NotNullable(true); x.Column("state"); x.Type <EnumType <OrderState> >(); }); ca.Property(x => x.Date, x => { x.NotNullable(true); x.Column("date"); }); ca.ManyToOne(c => c.Customer, a => { a.Column("customer_id"); a.NotNullable(true); a.Fetch(FetchKind.Select); a.Lazy(LazyRelation.NoProxy); a.Cascade(Cascade.All); }); ca.Set(x => x.Details, x => { x.Key(c => c.Column("order_id")); x.Fetch(CollectionFetchMode.Subselect); x.Inverse(true); x.Lazy(CollectionLazy.Extra); x.Cascade(Cascade.All | Cascade.DeleteOrphans); }, c => c.OneToMany()); }); mapper.Class <OrderDetail>(ca => { ca.Table("order_detail"); ca.Lazy(true); ca.Id(x => x.OrderDetailId, map => { map.Column("order_detail_id"); map.Generator(Generators.HighLow); }); ca.Property(x => x.Quantity, x => { x.NotNullable(true); x.Column("quantity"); }); ca.Property(x => x.ItemsPrice, x => { x.Formula("(quantity * (SELECT product.price FROM product WHERE product.product_id = product_id))"); x.Access(Accessor.None); x.Update(false); x.Type(NHibernateUtil.Decimal); x.Insert(false); }); ca.ManyToOne(x => x.Order, x => { x.NotNullable(true); x.Column("order_id"); x.Fetch(FetchKind.Select); x.Lazy(LazyRelation.NoProxy); x.Cascade(Cascade.None); }); ca.ManyToOne(x => x.Product, x => { x.NotNullable(true); x.Column("product_id"); x.Fetch(FetchKind.Select); x.Lazy(LazyRelation.NoProxy); x.Cascade(Cascade.None); }); }); mapper.Class <Product>(ca => { ca.Table("product"); ca.Lazy(true); ca.Id(x => x.ProductId, map => { map.Column("product_id"); map.Generator(Generators.HighLow); }); ca.NaturalId(x => x.Property(c => c.Name)); ca.Property(x => x.OrderCount, x => { x.Formula("(SELECT COUNT(1) FROM order_detail WHERE order_detail.product_id = product_id)"); }); ca.Property(x => x.Name, x => { x.NotNullable(true); x.Column("name"); }); ca.Property(x => x.Price, x => { x.NotNullable(true); x.Column("price"); }); ca.Property(x => x.Picture, x => { x.NotNullable(false); x.Column("picture"); x.Lazy(true); x.Type <ImageUserType>(new { ImageFormat = ImageFormat.Gif }); }); ca.Property(x => x.Specification, x => { x.NotNullable(true); x.Column("specification"); x.Lazy(true); x.Type <XDocType>(); }); ca.Set(x => x.OrderDetails, x => { x.Key(c => c.Column("product_id")); x.Inverse(true); x.Cascade(Cascade.All | Cascade.DeleteOrphans); x.Lazy(CollectionLazy.Lazy); }, c => c.OneToMany()); ca.Map(x => x.Attributes, c => { c.Cascade(Cascade.All); c.Lazy(CollectionLazy.Extra); c.Table("product_attribute"); c.Key(y => { y.Column("product_id"); y.NotNullable(true); }); }, k => { k.Element(e => { e.Column(y => { y.Name("name"); y.NotNullable(true); }); }); }, r => { r.Element(e => { e.Column("value"); e.NotNullable(true); }); }); }); HbmMapping mappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); cfg.AddDeserializedMapping(mappings, null); return(cfg); }