Ejemplo n.º 1
0
		public void AllInOne()
		{
			Configuration cfg = new Configuration();

			cfg.AddResource(BaseForMappings + "Extendshbm.allinone.hbm.xml", typeof(ExtendsFixture).Assembly);
			Assert.That(cfg.GetClassMapping(typeof (Customer).FullName), Is.Not.Null);
			Assert.That(cfg.GetClassMapping(typeof(Person).FullName), Is.Not.Null);
			Assert.That(cfg.GetClassMapping(typeof(Employee).FullName), Is.Not.Null);
		}
        public NHibernateTypeDescriptor(Type entityType, ICustomTypeDescriptor parent,
                                        Configuration nhibernateConfiguration, Type metaDataType)
            : base(parent)
        {
            Type metaDataType1 = metaDataType;

            while (entityType != null && entityType.Name.EndsWith("Proxy") &&
                   entityType.Assembly.GetName().Name.EndsWith("ProxyAssembly"))
                entityType = entityType.BaseType;
            this.entityType = entityType;
            this._nhibernateConfiguration = nhibernateConfiguration;
            _classMetadata = nhibernateConfiguration.GetClassMapping(this.entityType);
            _identifierCols = _classMetadata.Identifier.ColumnIterator;

            if (metaDataType1 != null)
            {
                var memberInfos =
                    metaDataType1.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
                foreach (var memberInfo in memberInfos)
                {
                    var attributes = memberInfo.GetCustomAttributes(false).Cast<Attribute>();
                    if (attributes.Any())
                        _metaDataAttributes.Add(memberInfo.Name, attributes);
                }
            }
        }
Ejemplo n.º 3
0
		public void IncrementGeneratorShouldIncludeClassLevelSchemaWhenGettingNextId()
		{
			System.Type thisType = GetType();
			Assembly thisAssembly = thisType.Assembly;

			Configuration cfg = new Configuration();
			cfg.AddResource(thisType.Namespace + ".Mappings.hbm.xml", thisAssembly);

			PersistentClass persistentClass = cfg.GetClassMapping(typeof(TestNH1061));
			// We know the ID generator is an IncrementGenerator.  The dialect does
			// not play a big role here, so just use the MsSql2000Dialect.
			IncrementGenerator generator =
				(IncrementGenerator)
				persistentClass.Identifier.CreateIdentifierGenerator(new Dialect.MsSql2000Dialect(), null, null, null);

			// I could not find a good seam to crack to test this.
			// This is not ideal as we are reflecting into a private variable to test.
			// On the other hand, the IncrementGenerator is rather stable, so I don't
			// think this would be a huge problem.
			// Having said that, if someone sees this and have a better idea to test,
			// please feel free to change it.
			FieldInfo sqlFieldInfo = generator.GetType().GetField("sql", BindingFlags.NonPublic | BindingFlags.Instance);
			string sql = (string)sqlFieldInfo.GetValue(generator);

			Assert.AreEqual("select max(Id) from test.TestNH1061", sql);
		}
Ejemplo n.º 4
0
		public void NwaitingForSuper()
		{
			Configuration cfg = new Configuration();

			cfg.AddResource(BaseForMappings + "Extendshbm.Customer.hbm.xml", typeof (ExtendsFixture).Assembly);
			Assert.That(cfg.GetClassMapping(typeof (Customer).FullName), Is.Null, "cannot be in the configuration yet!");

			cfg.AddResource(BaseForMappings + "Extendshbm.Employee.hbm.xml", typeof (ExtendsFixture).Assembly);
			Assert.That(cfg.GetClassMapping(typeof (Employee).FullName), Is.Null, "cannot be in the configuration yet!");

			cfg.AddResource(BaseForMappings + "Extendshbm.Person.hbm.xml", typeof (ExtendsFixture).Assembly);

			cfg.BuildMappings();
			Assert.That(cfg.GetClassMapping(typeof (Customer).FullName), Is.Not.Null);
			Assert.That(cfg.GetClassMapping(typeof (Person).FullName), Is.Not.Null);
			Assert.That(cfg.GetClassMapping(typeof (Employee).FullName), Is.Not.Null);
		}
Ejemplo n.º 5
0
		internal ForeignKeyInfo(Table table, ForeignKey fk, Configuration config)
			: base("FK_", table.Name, fk.ColumnIterator, null)
		{
			//note: the fk object has a ReferencedTable property, but it doesn't always seem to be set
			//the reference class property is always set, so we use it instead to get the referenced table 
			Table referencedTable = config.GetClassMapping(fk.ReferencedEntityName).Table;
			_referencedTable = referencedTable.Name;
			_referencedColumns = CollectionUtils.Map<Column, string>(
                referencedTable.PrimaryKey.ColumnIterator,
				delegate(Column column) { return column.Name; });
		}
 public void Process(string name, Configuration nhConfig)
 {
     foreach (var file in GetMappingFiles())
     {
         nhConfig.AddFile(file);
         // HBM.XML file must be named to match entity-name.
         var entityName = file.Name.Replace(".hbm.xml", string.Empty);
         var nhMappingInfo = nhConfig.GetClassMapping(entityName);
         var entityDefinition = definitionCreator.CreateFrom(nhMappingInfo);
         definitionProvider.Add(entityDefinition);
     }
 }
		public void ConfigureCacheOfCollectionWithOutEntity()
		{
			Configuration configure = new Configuration().Configure();
			configure.AddResource("NHibernate.Test.CfgTest.Loquacious.EntityToCache.hbm.xml", GetType().Assembly);

			configure.EntityCache<EntityToCache>(ce => ce.Collection(e => e.Elements, cc =>
			                                                                          	{
			                                                                          		cc.RegionName = "MyCollectionRegion";
			                                                                          		cc.Strategy =
			                                                                          			EntityCacheUsage.NonStrictReadWrite;
			                                                                          	}));

			var pc = (RootClass) configure.GetClassMapping(typeof (EntityToCache));
			Assert.That(pc.CacheConcurrencyStrategy, Is.Null);
		}
		public void ConfigureCacheOfClass()
		{
			Configuration configure = new Configuration().Configure();
			configure.AddResource("NHibernate.Test.CfgTest.Loquacious.EntityToCache.hbm.xml", GetType().Assembly);

			configure.EntityCache<EntityToCache>(ce =>
			                                     	{
			                                     		ce.Strategy = EntityCacheUsage.NonStrictReadWrite;
			                                     		ce.RegionName = "MyRegion";
			                                     	});

			var pc = (RootClass) configure.GetClassMapping(typeof (EntityToCache));
			Assert.That(pc.CacheConcurrencyStrategy,
			            Is.EqualTo(EntityCacheUsageParser.ToString(EntityCacheUsage.NonStrictReadWrite)));
			Assert.That(pc.CacheRegionName, Is.EqualTo("MyRegion"));
		}
Ejemplo n.º 9
0
		public void MissingSuper()
		{
			Configuration cfg = new Configuration();

			try
			{
				cfg.AddResource(BaseForMappings + "Extendshbm.Customer.hbm.xml", typeof (ExtendsFixture).Assembly);
				Assert.That(cfg.GetClassMapping(typeof (Customer).FullName), Is.Null, "cannot be in the configuration yet!");
				cfg.AddResource(BaseForMappings + "Extendshbm.Employee.hbm.xml", typeof (ExtendsFixture).Assembly);

				cfg.BuildSessionFactory();

				Assert.Fail("Should not be able to build sessionfactory without a Person");
			}
			catch (HibernateException) {}
		}
Ejemplo n.º 10
0
        public void WriteDomainDbInfo()
        {
            // 获取NHibernate 获取领域实体元数据集合
            // 通过NHibernateSession静态类 -> 获取默认工厂 -> 获取所有领域实体元数据
            var allClassMetadata = NHibernateSession.
                                   GetDefaultSessionFactory().GetAllClassMetadata();

            // 输出内容变量
            var str = new StringBuilder();

            // 遍历元数据
            foreach (var entry in allClassMetadata)
            {
                // 获取当前元数据
                var entity = ((SingleTableEntityPersister)entry.Value);
                // 获取实体映射的表名
                var tableName = entity.TableName;
                // 领域实体名称
                var entityName = entity.EntityName;
                // 领域实体Mapping对象
                var userClassMap = _nhConfig.GetClassMapping(entityName);
                // 领域实体主键名
                var primaryKey = userClassMap.Table.PrimaryKey.Columns.FirstOrDefault().Text;
                // 领域实体下的属性列表
                var column = userClassMap.Table.ColumnIterator;

                // 输出表头
                str.Append(string.Format("<H1>{0}({1})</H1>", tableName, entityName));

                // 获取实体描述
                // 使用反射dll -> 获取EntityDescAttribute特性描述内容
                var type = Type.GetType(entityName + "," + DomainDll);
                if (type != null)
                {
                    var attr = type.GetCustomAttributes(typeof(EntityDescAttribute), true);
                    if (attr.Length > 0)
                    {
                        str.Append(string.Format("<P>表描述:{0}</P>",
                                                 ((EntityDescAttribute)attr[0]).Description));
                    }
                }

                // 输出表格表头
                str.Append("<table width=\"100%\" " +
                           "border=\"1\" " +
                           "cellspacing=\"0\" " +
                           "bordercolor=\"#333\" >");
                str.Append("<tr style='background-color:#3AF;'>" +
                           "<td>序号</td>" +
                           "<td>数据库字段</td>" +
                           "<td>类型</td>" +
                           "<td>描述</td>" +
                           "<td>唯一约束</td>" +
                           "<td>允许为NULL</td>" +
                           "<td>是否主键</td>" +
                           "</tr>");
                // 遍历领域实体下的属性
                // 顺序索引
                var index = 0;
                foreach (var obj in column)
                {
                    // 属性描述
                    var attrDesc = "";

                    // 获取NHibernate Column对象
                    var item = (Column)obj.Value.ColumnIterator.FirstOrDefault();
                    if (item == null)
                    {
                        continue;
                    }

                    // 判断如果为领域实体唯一标识则不获取属性描述
                    if (primaryKey == item.Text)
                    {
                        //唯一标识
                        attrDesc = "唯一标识";
                    }
                    else
                    {
                        // 如果超出索引的 -> 判断为非数据库字段,为领域实体属性
                        // -> 跳出本次处理
                        if (index >= entity.PropertyNames.Count())
                        {
                            continue;
                        }

                        // 获取属性上的EntityPropertyDescAttribute特性描述内容
                        var memberItem = entity.PropertyNames[index];
                        if (type != null)
                        {
                            var property   = type.GetProperty(memberItem);
                            var memberAttr = property.GetCustomAttributes(
                                typeof(EntityPropertyDescAttribute), true);

                            if (memberAttr.Length > 0)
                            {
                                attrDesc = ((EntityPropertyDescAttribute)
                                            memberAttr[0]).Description;
                            }
                        }
                        ++index;
                    }

                    // 输出内容
                    str.Append(string.Format("<tr>" +
                                             "<td>{0}</td>" +
                                             "<td>{1}</td>" +
                                             "<td>{2}</td>" +
                                             "<td>{3}</td>" +
                                             "<td>{4}</td>" +
                                             "<td>{5}</td>" +
                                             "<td>{6}</td>" +
                                             "</tr>",
                                             index + 1,
                                             item.Text, GetType(item.Value.Type),
                                             attrDesc,
                                             item.IsUnique ? "Yes" : "No",
                                             item.IsNullable ? "Yes" : "No",
                                             (primaryKey == obj.Name) ? "Yes" : "No"));
                }
                str.Append("</table>");
            }
            // 输出数据库字典文件
            // 文件名
            const string outputFileName = "数据库字典.doc";
            // 输出文件夹路径
            string outputFilePath = Path.Combine(DB_FOLDER_PATH, outputFileName);

            // 输出操作
            File.WriteAllText(outputFilePath, str.ToString(), Encoding.GetEncoding("utf-8"));
        }
		public AbstractCollectionPersister(Mapping.Collection collection, ICacheConcurrencyStrategy cache, Configuration cfg,
		                                   ISessionFactoryImplementor factory)
		{
			this.factory = factory;
			this.cache = cache;
			if (factory.Settings.IsStructuredCacheEntriesEnabled)
			{
				cacheEntryStructure = collection.IsMap
				                      	? (ICacheEntryStructure) new StructuredMapCacheEntry()
				                      	: (ICacheEntryStructure) new StructuredCollectionCacheEntry();
			}
			else
			{
				cacheEntryStructure = new UnstructuredCacheEntry();
			}

			dialect = factory.Dialect;
			sqlExceptionConverter = factory.SQLExceptionConverter;
			collectionType = collection.CollectionType;
			role = collection.Role;
			entityName = collection.OwnerEntityName;
			ownerPersister = factory.GetEntityPersister(entityName);
			queryLoaderName = collection.LoaderName;
			nodeName = collection.NodeName;
			isMutable = collection.IsMutable;

			Table table = collection.CollectionTable;
			fetchMode = collection.Element.FetchMode;
			elementType = collection.Element.Type;
			isPrimitiveArray = collection.IsPrimitiveArray;
			isArray = collection.IsArray;
			subselectLoadable = collection.IsSubselectLoadable;
			qualifiedTableName = table.GetQualifiedName(dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);

			int spacesSize = 1 + collection.SynchronizedTables.Count;
			spaces = new string[spacesSize];
			int ispa = 0;
			spaces[ispa++] = qualifiedTableName;
			foreach (string s in collection.SynchronizedTables)
			{
				spaces[ispa++] = s;
			}

			sqlOrderByString = collection.OrderBy;
			hasOrder = sqlOrderByString != null;
			sqlOrderByStringTemplate = hasOrder
			                           	? Template.RenderOrderByStringTemplate(sqlOrderByString, dialect,
			                           	                                       factory.SQLFunctionRegistry)
			                           	: null;
			sqlWhereString = !string.IsNullOrEmpty(collection.Where) ? '(' + collection.Where + ')' : null;
			hasWhere = sqlWhereString != null;
			sqlWhereStringTemplate = hasWhere
			                         	? Template.RenderWhereStringTemplate(sqlWhereString, dialect, factory.SQLFunctionRegistry)
			                         	: null;
			hasOrphanDelete = collection.HasOrphanDelete;
			int batch = collection.BatchSize;
			if (batch == -1)
			{
				batch = factory.Settings.DefaultBatchFetchSize;
			}
			batchSize = batch;

			isVersioned = collection.IsOptimisticLocked;

			keyType = collection.Key.Type;
			int keySpan = collection.Key.ColumnSpan;
			keyColumnNames = new string[keySpan];
			keyColumnAliases = new string[keySpan];
			int k = 0;
			foreach (Column col in collection.Key.ColumnIterator)
			{
				keyColumnNames[k] = col.GetQuotedName(dialect);
				keyColumnAliases[k] = col.GetAlias(dialect);
				k++;
			}
			ISet distinctColumns = new HashedSet();
			CheckColumnDuplication(distinctColumns, collection.Key.ColumnIterator);

			#region Element

			IValue element = collection.Element;
			if (!collection.IsOneToMany)
			{
				CheckColumnDuplication(distinctColumns, element.ColumnIterator);
			}

			string elemNode = collection.ElementNodeName;
			if (elementType.IsEntityType)
			{
				string _entityName = ((EntityType) elementType).GetAssociatedEntityName();
				elementPersister = factory.GetEntityPersister(_entityName);
				if (elemNode == null)
				{
					elemNode = cfg.GetClassMapping(_entityName).NodeName;
				}
				// NativeSQL: collect element column and auto-aliases
			}
			else
			{
				elementPersister = null;
			}
			elementNodeName = elemNode;

			int elementSpan = element.ColumnSpan;
			elementColumnAliases = new string[elementSpan];
			elementColumnNames = new string[elementSpan];
			elementFormulaTemplates = new string[elementSpan];
			elementFormulas = new string[elementSpan];
			elementColumnIsSettable = new bool[elementSpan];
			elementColumnIsInPrimaryKey = new bool[elementSpan];
			bool isPureFormula = true;
			bool hasNotNullableColumns = false;
			int j = 0;
			foreach (ISelectable selectable in element.ColumnIterator)
			{
				elementColumnAliases[j] = selectable.GetAlias(dialect);
				if (selectable.IsFormula)
				{
					Formula form = (Formula) selectable;
					elementFormulaTemplates[j] = form.GetTemplate(dialect, factory.SQLFunctionRegistry);
					elementFormulas[j] = form.FormulaString;
				}
				else
				{
					Column col = (Column) selectable;
					elementColumnNames[j] = col.GetQuotedName(dialect);
					elementColumnIsSettable[j] = true;
					elementColumnIsInPrimaryKey[j] = !col.IsNullable;
					if (!col.IsNullable)
					{
						hasNotNullableColumns = true;
					}

					isPureFormula = false;
				}
				j++;
			}
			elementIsPureFormula = isPureFormula;

			//workaround, for backward compatibility of sets with no
			//not-null columns, assume all columns are used in the
			//row locator SQL
			if (!hasNotNullableColumns)
			{
				ArrayHelper.Fill(elementColumnIsInPrimaryKey, true);
			}

			#endregion

			#region INDEX AND ROW SELECT

			hasIndex = collection.IsIndexed;
			if (hasIndex)
			{
				// NativeSQL: collect index column and auto-aliases
				IndexedCollection indexedCollection = (IndexedCollection) collection;
				indexType = indexedCollection.Index.Type;
				int indexSpan = indexedCollection.Index.ColumnSpan;
				indexColumnNames = new string[indexSpan];
				indexFormulaTemplates = new string[indexSpan];
				indexFormulas = new string[indexSpan];
				indexColumnIsSettable = new bool[indexSpan];
				indexColumnAliases = new string[indexSpan];
				bool hasFormula = false;
				int i = 0;
				foreach (ISelectable selectable in indexedCollection.Index.ColumnIterator)
				{
					indexColumnAliases[i] = selectable.GetAlias(dialect);
					if (selectable.IsFormula)
					{
						Formula indexForm = (Formula) selectable;
						indexFormulaTemplates[i] = indexForm.GetTemplate(dialect, factory.SQLFunctionRegistry);
						indexFormulas[i] = indexForm.FormulaString;
						hasFormula = true;
					}
					else
					{
						Column indexCol = (Column) selectable;
						indexColumnNames[i] = indexCol.GetQuotedName(dialect);
						indexColumnIsSettable[i] = true;
					}
					i++;
				}
				indexContainsFormula = hasFormula;
				baseIndex = indexedCollection.IsList ? ((List) indexedCollection).BaseIndex : 0;

				indexNodeName = indexedCollection.IndexNodeName;
				CheckColumnDuplication(distinctColumns, indexedCollection.Index.ColumnIterator);
			}
			else
			{
				indexContainsFormula = false;
				indexColumnIsSettable = null;
				indexFormulaTemplates = null;
				indexFormulas = null;
				indexType = null;
				indexColumnNames = null;
				indexColumnAliases = null;
				baseIndex = 0;
				indexNodeName = null;
			}

			hasIdentifier = collection.IsIdentified;
			if (hasIdentifier)
			{
				if (collection.IsOneToMany)
				{
					throw new MappingException("one-to-many collections with identifiers are not supported.");
				}
				IdentifierCollection idColl = (IdentifierCollection) collection;
				identifierType = idColl.Identifier.Type;

				Column col = null;
				foreach (Column column in idColl.Identifier.ColumnIterator)
				{
					col = column;
					break;
				}

				identifierColumnName = col.GetQuotedName(dialect);
				identifierColumnAlias = col.GetAlias(dialect);
				identifierGenerator =
					idColl.Identifier.CreateIdentifierGenerator(factory.Dialect, factory.Settings.DefaultCatalogName,
					                                            factory.Settings.DefaultSchemaName, null);
				// NH see : identityDelegate declaration
				IPostInsertIdentifierGenerator pig = (identifierGenerator as IPostInsertIdentifierGenerator);
				if (pig != null)
				{
					identityDelegate = pig.GetInsertGeneratedIdentifierDelegate(this, Factory, UseGetGeneratedKeys());
				}
				else
				{
					identityDelegate = null;
				}

				CheckColumnDuplication(distinctColumns, idColl.Identifier.ColumnIterator);
			}
			else
			{
				identifierType = null;
				identifierColumnName = null;
				identifierColumnAlias = null;
				identifierGenerator = null;
				identityDelegate = null;
			}

			#endregion

			#region GENERATE THE SQL

			// NH Different behavior : for the Insert SQL we are managing isPostInsertIdentifier (not supported in H3.2.5) 
			if (collection.CustomSQLInsert == null)
			{
				if (!IsIdentifierAssignedByInsert)
				{
					sqlInsertRowString = GenerateInsertRowString();
				}
				else
				{
					sqlInsertRowString = GenerateIdentityInsertRowString();
				}
				insertCallable = false;
				insertCheckStyle = ExecuteUpdateResultCheckStyle.Count;
			}
			else
			{
				SqlType[] parmsTypes = GenerateInsertRowString().ParameterTypes;
				sqlInsertRowString = new SqlCommandInfo(collection.CustomSQLInsert, parmsTypes);
				insertCallable = collection.IsCustomInsertCallable;
				insertCheckStyle = collection.CustomSQLInsertCheckStyle
				                   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(collection.CustomSQLInsert, insertCallable);
			}

			sqlUpdateRowString = GenerateUpdateRowString();
			if (collection.CustomSQLUpdate == null)
			{
				updateCallable = false;
				updateCheckStyle = ExecuteUpdateResultCheckStyle.Count;
			}
			else
			{
				sqlUpdateRowString = new SqlCommandInfo(collection.CustomSQLUpdate, sqlUpdateRowString.ParameterTypes);
				updateCallable = collection.IsCustomUpdateCallable;
				updateCheckStyle = collection.CustomSQLUpdateCheckStyle
				                   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(collection.CustomSQLUpdate, updateCallable);
			}

			sqlDeleteRowString = GenerateDeleteRowString();
			if (collection.CustomSQLDelete == null)
			{
				deleteCallable = false;
				deleteCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}
			else
			{
				sqlDeleteRowString = new SqlCommandInfo(collection.CustomSQLDelete, sqlDeleteRowString.ParameterTypes);
				deleteCallable = collection.IsCustomDeleteCallable;
				deleteCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}

			sqlDeleteString = GenerateDeleteString();
			if (collection.CustomSQLDeleteAll == null)
			{
				deleteAllCallable = false;
				deleteAllCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}
			else
			{
				sqlDeleteString = new SqlCommandInfo(collection.CustomSQLDeleteAll, sqlDeleteString.ParameterTypes);
				deleteAllCallable = collection.IsCustomDeleteAllCallable;
				deleteAllCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}

		    isCollectionIntegerIndex = collection.IsIndexed && !collection.IsMap;
			sqlDetectRowByIndexString = GenerateDetectRowByIndexString();
			sqlDetectRowByElementString = GenerateDetectRowByElementString();
			sqlSelectRowByIndexString = GenerateSelectRowByIndexString();

			LogStaticSQL();

			#endregion

			isLazy = collection.IsLazy;
			isExtraLazy = collection.ExtraLazy;
			isInverse = collection.IsInverse;

			if (collection.IsArray)
			{
				elementClass = ((Array) collection).ElementClass;
			}
			else
			{
				// for non-arrays, we don't need to know the element class
				elementClass = null;
			}

			if (elementType.IsComponentType)
			{
				elementPropertyMapping =
					new CompositeElementPropertyMapping(elementColumnNames, elementFormulaTemplates,
					                                    (IAbstractComponentType) elementType, factory);
			}
			else if (!elementType.IsEntityType)
			{
				elementPropertyMapping = new ElementPropertyMapping(elementColumnNames, elementType);
			}
			else
			{
				elementPropertyMapping = elementPersister as IPropertyMapping;
				if (elementPropertyMapping == null)
				{
					elementPropertyMapping = new ElementPropertyMapping(elementColumnNames, elementType);
				}
			}

			// Handle any filters applied to this collection
			filterHelper = new FilterHelper(collection.FilterMap, dialect, factory.SQLFunctionRegistry);

			// Handle any filters applied to this collection for many-to-many
			manyToManyFilterHelper = new FilterHelper(collection.ManyToManyFilterMap, dialect, factory.SQLFunctionRegistry);
			manyToManyWhereString = !string.IsNullOrEmpty(collection.ManyToManyWhere)
			                        	? "( " + collection.ManyToManyWhere + " )"
			                        	: null;
			manyToManyWhereTemplate = manyToManyWhereString == null
			                          	? null
			                          	: Template.RenderWhereStringTemplate(manyToManyWhereString, factory.Dialect,
			                          	                                     factory.SQLFunctionRegistry);
			manyToManyOrderByString = collection.ManyToManyOrdering;
			manyToManyOrderByTemplate = manyToManyOrderByString == null
			                            	? null
			                            	: Template.RenderOrderByStringTemplate(manyToManyOrderByString, factory.Dialect,
			                            	                                       factory.SQLFunctionRegistry);
			InitCollectionPropertyMap();
		}
Ejemplo n.º 12
0
		public void JoinedSubclassAndEntityNamesOnly()
		{
			Configuration cfg = new Configuration();

			cfg.AddResource(BaseForMappings + "Extendshbm.entitynames.hbm.xml", typeof (ExtendsFixture).Assembly);

			cfg.BuildMappings();
			Assert.That(cfg.GetClassMapping("EntityHasName"), Is.Not.Null);
			Assert.That(cfg.GetClassMapping("EntityCompany"), Is.Not.Null);
		}
Ejemplo n.º 13
0
		public void UnionSubclass()
		{
			Configuration cfg = new Configuration();

			cfg.AddResource(BaseForMappings + "Extendshbm.unionsubclass.hbm.xml", typeof (ExtendsFixture).Assembly);

			cfg.BuildMappings();

			Assert.That(cfg.GetClassMapping(typeof (Person).FullName), Is.Not.Null);
			Assert.That(cfg.GetClassMapping(typeof (Customer).FullName), Is.Not.Null);
		}
Ejemplo n.º 14
0
		public void EntityNamesWithPackageFailureExpectedDiffFiles()
		{
			Configuration cfg = new Configuration();
			cfg.AddResource(BaseForMappings + "Extendshbm.packageentitynamesf1.hbm.xml", typeof(ExtendsFixture).Assembly);
			cfg.AddResource(BaseForMappings + "Extendshbm.packageentitynamesf2.hbm.xml", typeof(ExtendsFixture).Assembly);

			cfg.BuildMappings();

			Assert.That(cfg.GetClassMapping("EntityHasName"), Is.Not.Null);
			Assert.That(cfg.GetClassMapping("EntityCompany"), Is.Not.Null);
		}
Ejemplo n.º 15
0
        public void Compile(NHcfg.Configuration configuration)
        {
            var mapper = new ModelMapperWithNamingConventions();

            mapper.IsEntity((type, declared) => MappingHelper.IsEntity(type));
            mapper.IsRootEntity((type, declared) => MappingHelper.IsRootEntity(type));
            mapper.IsTablePerClass((type, declared) =>
            {
                var discriminator = MappingHelper.GetDiscriminatorColumn(type);
                return(string.IsNullOrWhiteSpace(discriminator));
            });
            mapper.IsTablePerClassHierarchy((type, declared) =>
            {
                var discriminator = MappingHelper.GetDiscriminatorColumn(type);
                return(!string.IsNullOrWhiteSpace(discriminator));
            });
            mapper.IsTablePerConcreteClass((type, declared) => false);

            mapper.IsOneToMany((mi, declared) =>
            {
                if (Attribute.IsDefined(mi, (typeof(ManyToManyAttribute))))
                {
                    return(false);
                }

                return(declared || _defaultMapper.ModelInspector.IsOneToMany(mi));
            });

            mapper.IsManyToMany((mi, declared) =>
            {
                if (Attribute.IsDefined(mi, (typeof(ManyToManyAttribute))))
                {
                    return(true);
                }

                return(declared || _defaultMapper.ModelInspector.IsManyToAny(mi));
            });

            mapper.IsPersistentProperty((mi, declared) =>
            {
                if (!NhMappingHelper.IsPersistentProperty(mi))
                {
                    return(false);
                }

                return(_defaultMapper.ModelInspector.IsPersistentProperty(mi));
            });

            mapper.BeforeMapSubclass += (modelInspector, type, subclassCustomizer) =>
            {
                var discriminatorValue = MappingHelper.GetDiscriminatorValue(type);

                subclassCustomizer.DiscriminatorValue(discriminatorValue);


                var joinPropAttribute = type.GetAttribute <JoinedPropertyAttribute>();
                if (joinPropAttribute != null)
                {
                    if (string.IsNullOrWhiteSpace(joinPropAttribute.TableName))
                    {
                        throw new Exception($"{nameof(JoinedPropertyAttribute.TableName)} is mandatory for `{joinPropAttribute.GetType().Name}`, check class `{type.FullName}`");
                    }

                    if (subclassCustomizer is NMIMPL.SubclassMapper subclassMapper)
                    {
                        // add join with provided table name, all properties will be added using current conventions and placed to the corresponding group using SplitGroupId = TableName
                        subclassMapper.Join(joinPropAttribute.TableName, j =>
                        {
                            j.Table(joinPropAttribute.TableName);

                            j.Fetch(FetchKind.Join);

                            j.Key(k =>
                            {
                                k.Column("Id");
                            });
                        });
                    }
                }
            };

            mapper.SplitsFor((type, definedSplits) =>
            {
                var splits = definedSplits.ToList();

                if (type.Name.Contains("TestProcessConfiguration"))
                {
                }

                var joinPropAttribute = type.GetAttribute <JoinedPropertyAttribute>();
                if (joinPropAttribute != null && !splits.Contains(joinPropAttribute.TableName))
                {
                    splits.Add(joinPropAttribute.TableName);
                }

                return(splits);
            });

            mapper.IsTablePerClassSplit((definition, b) => true);

            mapper.BeforeMapElement += (modelInspector, member, collectionRelationElementCustomizer) =>
            {
            };

            mapper.BeforeMapProperty += (modelInspector, member, propertyCustomizer) =>
            {
                var propertyType = member.LocalMember.GetPropertyOrFieldType();

                var    columnName = MappingHelper.GetColumnName(member.LocalMember);
                string sqlType    = null;
                IType  columnType = null;

                if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
                {
                    columnType = NHibernateUtil.DateTime;
                    sqlType    = "DateTime";
                }
                else
                if (member.LocalMember.GetAttribute <StringLengthAttribute>()?.MaximumLength == int.MaxValue)
                //if (Attribute.IsDefined(member.LocalMember, (typeof(StringClobAttribute))))
                {
                    columnType = NHibernateUtil.StringClob;
                    sqlType    = "nvarchar(max)";
                }

                if (columnType != null)
                {
                    propertyCustomizer.Type(columnType);
                }

                if (Attribute.GetCustomAttribute(member.LocalMember, typeof(ReadonlyPropertyAttribute), true) is ReadonlyPropertyAttribute readonlyAttribute)
                {
                    propertyCustomizer.Insert(readonlyAttribute.Insert);
                    propertyCustomizer.Update(readonlyAttribute.Update);
                }

                propertyCustomizer.Column(c =>
                {
                    c.Name(columnName);
                    if (!string.IsNullOrWhiteSpace(sqlType))
                    {
                        c.SqlType(sqlType);
                    }
                });
            };

            mapper.IsPersistentId((mi, d) =>
            {
                var isId = mi.Name.Equals("Id", StringComparison.InvariantCultureIgnoreCase);
                return(isId);
            });
            mapper.BeforeMapClass += (modelInspector, type, classCustomizer) =>
            {
                var tableName = MappingHelper.GetTableName(type);

                classCustomizer.Table(tableName);

                var imMutable = type.HasAttribute <ImMutableAttribute>(true);
                if (imMutable)
                {
                    classCustomizer.Mutable(false);
                }

                if (MappingHelper.IsEntity(type))
                {
                    try
                    {
                        var idProp = type.GetProperty("Id");
                        if (idProp != null)
                        // note: Id may be missing when entity has hand-written mapping but isn't derived from EntityWithTypedId<> (for example: NhIdentityUserLogin)
                        {
                            if (tableName.StartsWith("Abp") && (idProp.PropertyType == typeof(Int64) || idProp.PropertyType == typeof(int)))
                            {
                                // temporary map `Abp` tables without hilo
                                classCustomizer.Id(p =>
                                {
                                    p.Column("Id");
                                    p.Generator(NHGens.Identity);
                                });
                            }
                            else
                            {
                                var idColumn = idProp.GetAttribute <ColumnAttribute>()?.Name ?? "Id";

                                // get Id mapper
                                var idMapper = _idMapper.Invoke(idProp.PropertyType);
                                if (idMapper != null)
                                {
                                    classCustomizer.Id(p =>
                                    {
                                        idMapper.Invoke(p);
                                        p.Column(idColumn);
                                    });
                                }
                            }
                        }
                        else
                        {
                        }
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }

                var discriminatorColumn = MappingHelper.GetDiscriminatorColumn(type);
                if (!string.IsNullOrWhiteSpace(discriminatorColumn))
                {
                    classCustomizer.Discriminator(d =>
                    {
                        d.Column(discriminatorColumn);

                        if (MappingHelper.GetFilterUnknownDiscriminatorsFlag(type))
                        {
                            d.Force(true);
                        }
                    });

                    var discriminatorValue = MappingHelper.GetDiscriminatorValue(type);

                    classCustomizer.DiscriminatorValue(discriminatorValue);
                }

                // IMayHaveTenant support
                if (typeof(IMayHaveTenant).IsAssignableFrom(type))
                {
                    classCustomizer.Filter("MayHaveTenant", m =>
                    {
                    });
                }

                // ISoftDelete support
                if (typeof(ISoftDelete).IsAssignableFrom(type))
                {
                    classCustomizer.Filter("SoftDelete", m =>
                    {
                    });
                }
            };

            mapper.BeforeMapManyToOne += (modelInspector, propertyPath, map) =>
            {
                string columnPrefix = MappingHelper.GetColumnPrefix(propertyPath.LocalMember.DeclaringType);

                var lazyAttribute = propertyPath.LocalMember.GetAttribute <LazyAttribute>(true);
                var lazyRelation  = lazyAttribute != null?lazyAttribute.GetLazyRelation() : _defaultLazyRelation;

                if (lazyRelation != null)
                {
                    map.Lazy(lazyRelation);
                }

                var foreignKeyAttribute = propertyPath.LocalMember.GetAttribute <ForeignKeyAttribute>(true);
                var foreignKeyColumn    = foreignKeyAttribute != null
                    ? foreignKeyAttribute.Name
                    : columnPrefix + propertyPath.LocalMember.Name + "Id";

                //map.NotFound(NotFoundMode.Ignore); disabled due to performance issues, this option breaks lazy loading
                map.Column(foreignKeyColumn);

                var directlyMappedFk = propertyPath.LocalMember.DeclaringType?.GetProperty(foreignKeyColumn);

                if (foreignKeyColumn.ToLower() == "id" || directlyMappedFk != null)
                {
                    map.Insert(false);
                    map.Update(false);
                }

                var cascadeAttribute = propertyPath.LocalMember.GetAttribute <CascadeAttribute>(true);
                map.Cascade(cascadeAttribute?.Cascade ?? Cascade.Persist);
                map.Class(propertyPath.LocalMember.GetPropertyOrFieldType());
            };

            mapper.BeforeMapBag += (modelInspector, propertyPath, map) => {
                var inversePropertyAttribute = propertyPath.LocalMember.GetAttribute <InversePropertyAttribute>(true);
                if (inversePropertyAttribute != null)
                {
                    map.Key(keyMapper => keyMapper.Column(inversePropertyAttribute.Property));
                }
                else
                {
                    map.Key(keyMapper => keyMapper.Column(propertyPath.GetContainerEntity(modelInspector).Name + "Id"));
                }

                map.Cascade(Cascade.All);
                map.Lazy(CollectionLazy.Lazy);

                var bagMapper = map as NMIMPL.BagMapper;

                var manyToManyAttribute = propertyPath.LocalMember.GetAttribute <ManyToManyAttribute>(true);

                if (manyToManyAttribute != null)
                {
                    map.Cascade(Cascade.None);

                    if (!string.IsNullOrEmpty(manyToManyAttribute.Table))
                    {
                        map.Table(manyToManyAttribute.Table);
                    }

                    if (!string.IsNullOrEmpty(manyToManyAttribute.KeyColumn))
                    {
                        map.Key(keyMapper => keyMapper.Column(manyToManyAttribute.KeyColumn));
                    }
                    if (!string.IsNullOrEmpty(manyToManyAttribute.Where))
                    {
                        map.Where(manyToManyAttribute.Where);
                    }
                    if (!string.IsNullOrEmpty(manyToManyAttribute.OrderBy))
                    {
                        map.OrderBy(manyToManyAttribute.OrderBy);
                    }
                }
                else
                {
                    if (bagMapper != null && typeof(ISoftDelete).IsAssignableFrom(bagMapper.ElementType))
                    {
                        //TODO: Check IsDeletedColumn for Many-To-Many
                        map.Where($"{SheshaDatabaseConsts.IsDeletedColumn} = 0");
                    }
                }
            };

            mapper.BeforeMapManyToMany += (modelInspector, propertyPath, map) => {
                //map.NotFound(NotFoundMode.Ignore); disabled due to performance issues, this option breaks lazy loading

                var manyToManyAttribute = propertyPath.LocalMember.GetAttribute <ManyToManyAttribute>(true);
                if (manyToManyAttribute != null)
                {
                    if (!string.IsNullOrEmpty(manyToManyAttribute.ChildColumn))
                    {
                        map.Column(manyToManyAttribute.ChildColumn);
                    }
                }
            };

            foreach (var assembly in _assemblies)
            {
                var allTypes = !assembly.IsDynamic
                    ? assembly.GetExportedTypes()
                    : assembly.GetTypes();
                var allEntities = allTypes.Where(t => MappingHelper.IsEntity(t)).ToList();
                foreach (var entityType in allEntities)
                {
                    var classMapping = configuration.GetClassMapping(entityType);
                    if (classMapping == null)
                    {
                        _entitiesToMap.Add(entityType);
                    }
                }

                var mappingOverride = allTypes.Where(t => IsClassMapping(t) && !t.IsAbstract).ToList();
                foreach (var @override in mappingOverride)
                {
                    try
                    {
                        var entityType = GetEntityTypeByMapping(@override);

                        if (entityType.IsEntityType())
                        {
                            _defaultMapper.AddMapping(@override);
                            mapper.AddMapping(@override);

                            if (entityType != null && !entityType.IsAbstract && !_entitiesToMap.Contains(entityType))
                            {
                                _entitiesToMap.Add(entityType);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }
            }

            // sort entity types by hierarchy
            _entitiesToMap = MappingHelper.SortEntityTypesByInheritance(_entitiesToMap);

            /* for debug
             * foreach (var ent in _entitiesToMap)
             * {
             *  try
             *  {
             *      var mapping1 = mapper.CompileMappingFor(new List<Type> { ent });
             *  }
             *  catch (Exception e)
             *  {
             *      throw;
             *  }
             * }
             */

            HbmMapping mapping = mapper.CompileMappingFor(_entitiesToMap);

            configuration.AddDeserializedMapping(mapping, "AutoMapping");

            LastCompiledXml = mapping.AsString();
        }
Ejemplo n.º 16
0
        private static void AddAnnotations(Configuration configuration, SrmSettings settings, AnnotationDef.AnnotationTarget annotationTarget, Type persistentClass)
        {
            var mapping = configuration.GetClassMapping(persistentClass);
            foreach (var annotationDef in settings.DataSettings.AnnotationDefs)
            {
                if (!annotationDef.AnnotationTargets.Contains(annotationTarget))
                {
                    continue;
                }
                string columnName = AnnotationDef.GetColumnName(annotationDef.Name);
                Type accessorType;
                switch (annotationDef.Type)
                {
                    case AnnotationDef.AnnotationType.number:
                        accessorType = typeof (NumberAnnotationPropertyAccessor);
                        break;
                    case AnnotationDef.AnnotationType.true_false:
                        accessorType = typeof (BoolAnnotationPropertyAccessor);
                        break;
                    default:
                        accessorType = typeof (AnnotationPropertyAccessor);
                        break;
                }

                AddColumn(mapping, columnName, accessorType);
            }
        }
Ejemplo n.º 17
0
        private static void AddRatioColumns(Configuration configuration, SrmSettings settings)
        {
            var mappingPeptide = configuration.GetClassMapping(typeof(DbPeptideResult));
            var mappingPrec = configuration.GetClassMapping(typeof(DbPrecursorResult));
            var mappingTran = configuration.GetClassMapping(typeof(DbTransitionResult));

            var mods = settings.PeptideSettings.Modifications;
            var standardTypes = mods.RatioInternalStandardTypes;
            var labelTypes = mods.GetModificationTypes().ToArray();
            if (labelTypes.Length > 2)
            {
                foreach (var standardType in standardTypes)
                {
                    foreach (var labelType in labelTypes)
                    {
                        if (ReferenceEquals(labelType, standardType))
                            continue;

                        AddColumn(mappingPeptide,
                                  RatioPropertyAccessor.PeptideRatioProperty(labelType, standardType).ColumnName,
                                  typeof (RatioPropertyAccessor));
                        AddColumn(mappingPeptide,
                                  RatioPropertyAccessor.PeptideRdotpProperty(labelType, standardType).ColumnName,
                                  typeof (RatioPropertyAccessor));
                    }

                    // Only add TotalAreaRatioTo<label type> and AreaRatioTo<label type> columns
                    // when there is more than one internal standard label type, because that
                    // is the only time that data is added to these columns in the database.
                    if (standardTypes.Count > 1)
                    {
                        AddColumn(mappingPrec, RatioPropertyAccessor.PrecursorRatioProperty(standardType).ColumnName,
                                  typeof (RatioPropertyAccessor));
                        AddColumn(mappingPrec, RatioPropertyAccessor.PrecursorRdotpProperty(standardType).ColumnName,
                                  typeof (RatioPropertyAccessor));
                        AddColumn(mappingTran, RatioPropertyAccessor.TransitionRatioProperty(standardType).ColumnName,
                                  typeof (RatioPropertyAccessor));
                    }
                }
            }

            if (settings.HasGlobalStandardArea)
            {
                foreach (var labelType in labelTypes)
                {
                    AddColumn(mappingPeptide, RatioPropertyAccessor.PeptideRatioProperty(labelType, null).ColumnName, typeof(RatioPropertyAccessor));
                }
                AddColumn(mappingPrec, RatioPropertyAccessor.PrecursorRatioProperty(null).ColumnName, typeof(RatioPropertyAccessor));
                AddColumn(mappingTran, RatioPropertyAccessor.TransitionRatioProperty(null).ColumnName, typeof(RatioPropertyAccessor));
            }
        }
        public virtual void Configure(Configuration cfg)
        {
            EnsureMappingsBuilt();

            foreach (var mapping in compiledMappings)
            {
                var serializer = new MappingXmlSerializer();
                XmlDocument document = serializer.Serialize(mapping);

                if (cfg.GetClassMapping(mapping.Classes.First().Type) == null)
                    cfg.AddDocument(document);
            }
        }
        private static string GetDirectoryProviderName(System.Type clazz, Configuration cfg)
        {
            // Get the most specialized (ie subclass > superclass) non default index name
            // If none extract the name from the most generic (superclass > subclass) [Indexed] class in the hierarchy
            PersistentClass pc = cfg.GetClassMapping(clazz);
            System.Type rootIndex = null;
            do
            {
                IndexedAttribute indexAnn = AttributeUtil.GetIndexed(pc.MappedClass);
                if (indexAnn != null)
                {
                    if (string.IsNullOrEmpty(indexAnn.Index) == false)
                    {
                        return indexAnn.Index;
                    }

                    rootIndex = pc.MappedClass;
                }

                pc = pc.Superclass;
            } while (pc != null);

            // there is nobody out there with a non default [Indexed(Index = "fo")]
            if (rootIndex != null)
            {
                return rootIndex.Name;
            }

            throw new HibernateException("Trying to extract the index name from a non @Indexed class: " + clazz);
        }