public override PropertyDescriptorCollection GetProperties()
 {
     if (_properties == null)
     {
         bool hasEntityAttributes = false;
         _properties = base.GetProperties();
         var list = new List<PropertyDescriptor>();
         foreach (PropertyDescriptor descriptor in _properties)
         {
             List<Attribute> attrs = GetEntityMemberAttributes(descriptor).ToList();
             if (_metaDataAttributes.ContainsKey(descriptor.Name))
                 attrs.AddRange(_metaDataAttributes[descriptor.Name]);
             if (attrs.Any())
             {
                 hasEntityAttributes = true;
                 list.Add(new PropertyDescriptorWrapper(descriptor, attrs.ToArray()));
             }
             else
             {
                 list.Add(descriptor);
             }
         }
         if (hasEntityAttributes)
             _properties = new PropertyDescriptorCollection(list.ToArray(), true);
     }
     return _properties;
 }
 public void viewroots() {
     var result = new List<string>();
     result.Add(MonoRailConfiguration.GetConfig().ViewEngineConfig.ViewPathRoot);
    
     foreach (var path in MonoRailConfiguration.GetConfig().ViewEngineConfig.PathSources) {
         result.Add(path);
     }
     PropertyBag["result"] = result;
 }
        public ISlabInfo[] GetSlabInfoByTimeInterval(long aFrom, long aTo)
        {
            try {
                using (var session = NHibernateHelper.OpenSession()) {
                    var entitys = session.CreateCriteria(typeof(SlabInfoEntity))
                    .Add(Restrictions.Between("StartScanTime", aFrom, aTo))
                    .List<SlabInfoEntity>();

                    var results = new List<ISlabInfo>();
                    foreach (var entity in entitys) {
                        results.Add(new SlabInfoImpl {
                            Id = entity.Id,
                            Number = entity.Number,
                            StandartSizeId = entity.StandartSizeId,
                            StartScanTime = entity.StartScanTime,
                            EndScanTime = entity.EndScanTime
                        });
                    }

                    return results.ToArray();
                }
            }
            catch (Exception ex) {
                logger.Error("Ошибка при чтении SlabInfo: " + ex.Message);
                return null;
            }
        }
示例#4
0
        public List<DiskContentModel> GetContentList(Directories dir)
        {
            var listOfDirectories = dir.SubFolder.ToList();
            var listOfContent = new List<DiskContentModel>();

            foreach (var dirs in listOfDirectories)
            {
                listOfContent.Add(Mapper.Map<Directories, DiskContentModel>(dirs));
            }
            return listOfContent;
        }
示例#5
0
        static void Main(string[] args)
        {
            var results = new List<TestResult>();
            results.Add(AdoDataAccess());
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);

            results.Add(DapperDataAccess());
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);

            results.Add(EfDataAccess());
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);

            results.Add(EfFastDataAccess());
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);

            results.Add(NhDataAccess());

            ConsoleTable.From(results).Write();

            Console.WriteLine("Teste finalizado");
            Console.ReadKey();
        }
		public override void CreateForeignKeyOfEntity(string entityName)
		{
			if (!HasFormula && !string.Equals("none", ForeignKeyName, StringComparison.InvariantCultureIgnoreCase))
			{
				var referencedColumns = new List<Column>(_prototype.ColumnSpan);
				foreach (Column column in _prototype.ColumnIterator)
				{
					referencedColumns.Add(column);
				}

				ForeignKey fk = Table.CreateForeignKey(ForeignKeyName, ConstraintColumns, entityName, referencedColumns);
				fk.CascadeDeleteEnabled = IsCascadeDeleteEnabled;
			}
		}
        public string[] GenerateSchemaDropScriptAuxiliaryDatabaseObjects(Func<IAuxiliaryDatabaseObject, bool> predicate)
        {
            Dialect dialect = Dialect.GetDialect(Properties);
            string defaultCatalog = PropertiesHelper.GetString("default_catalog", Properties, null);
            string defaultSchema = PropertiesHelper.GetString("default_schema", Properties, null);
            List<string> list = new List<string>();
            foreach (IAuxiliaryDatabaseObject obj2 in auxiliaryDatabaseObjects.Where(predicate))
            {
                if (obj2.AppliesToDialect(dialect))
                {
                    list.Add(obj2.SqlDropString(dialect,defaultCatalog, defaultSchema));
                }
            }

            return list.ToArray();
        }
 public AnalysisChromatograms(PeptideFileAnalysis peptideFileAnalysis)
 {
     PeptideFileAnalysis = peptideFileAnalysis;
     FirstTime = peptideFileAnalysis.FirstTime;
     LastTime = peptideFileAnalysis.LastTime;
     Chromatograms = new List<ChromatogramGenerator.Chromatogram>();
     for (int charge = PeptideAnalysis.MinCharge; charge <= PeptideAnalysis.MaxCharge; charge ++)
     {
         var mzs = PeptideAnalysis.TurnoverCalculator.GetMzs(charge);
         for (int massIndex = 0; massIndex < mzs.Count; massIndex ++)
         {
             Chromatograms.Add(new ChromatogramGenerator.Chromatogram(new MzKey(charge, massIndex), mzs[massIndex]));
         }
     }
     ScanIndexes = new List<int>();
     Times = new List<double>();
 }
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var siteCopyOptions = new List<SiteCopyOption>();

            NameValueCollection form = controllerContext.HttpContext.Request.Form;
            IEnumerable<string> keys = form.AllKeys.Where(s => s.StartsWith("sco-"));

            foreach (string key in keys)
            {
                string value = form[key];
                int id;
                string typeName = key.Substring(4);
                Type type = TypeHelper.GetTypeByName(typeName);
                if (int.TryParse(value, out id) && type != null)
                {
                    siteCopyOptions.Add(new SiteCopyOption {SiteCopyActionType = type, SiteId = id});
                }
            }

            return siteCopyOptions;
        }
示例#10
0
		/// <summary>
		/// Provide the list of progressive-paths
		/// </summary>
		/// <param name="source"></param>
		/// <returns>
		/// Given a path as : Pl1.Pl2.Pl3.Pl4.Pl5 returns paths-sequence as:
		/// Pl5
		/// Pl4.Pl5
		/// Pl3.Pl4.Pl5
		/// Pl2.Pl3.Pl4.Pl5
		/// Pl1.Pl2.Pl3.Pl4.Pl5
		/// </returns>
		public static IEnumerable<PropertyPath> InverseProgressivePath(this PropertyPath source)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			var analizing = source;
			var returnLocalMembers = new List<MemberInfo>(10);
			do
			{
				returnLocalMembers.Add(analizing.LocalMember);
				PropertyPath progressivePath = null;
				for (int i = returnLocalMembers.Count -1; i >= 0; i--)
				{
					progressivePath = new PropertyPath(progressivePath, returnLocalMembers[i]);
				}
				yield return progressivePath;
				analizing = analizing.PreviousPath;
			}
			while (analizing != null);
		}
示例#11
0
        private void SyncRoles(IList<RoleCheckBox> checkBoxes, IList<Role> roles)
        {
            var selectedRoles = new List<Role>();

            foreach (var role in Database.Session.Query<Role>())
            {
                var checkbox = checkBoxes.Single(a => a.Id == role.Id);
                checkbox.Name = role.Name;
                if(checkbox.IsChecked)
                    selectedRoles.Add(role);
            }

            foreach (var toAdd in selectedRoles.Where(a => !roles.Contains(a)))
                roles.Add(toAdd);

            foreach (var toRemove in roles.Where(a => !selectedRoles.Contains(a)).ToList())
                roles.Remove(toRemove);
        }
示例#12
0
		/// <summary>
		/// Return the names of all persistent (mapped) classes that extend or implement the
		/// given class or interface, accounting for implicit/explicit polymorphism settings
		/// and excluding mapped subclasses/joined-subclasses of other classes in the result.
		/// </summary>
		public string[] GetImplementors(string className)
		{
			System.Type clazz = null;

			// NH Different implementation for performance: a class without at least a namespace sure can't be found by reflection
			if (className.IndexOf('.') > 0)
			{
				IEntityPersister checkPersister;
				// NH Different implementation: we have better performance checking, first of all, if we know the class
				// and take the System.Type directly from the persister (className have high probability to be entityName)
				if (entityPersisters.TryGetValue(className, out checkPersister))
				{
					if(!checkPersister.EntityMetamodel.HasPocoRepresentation)
					{
						// we found the persister but it is a dynamic entity without class
						return new[] { className };
					}
					// NH : take care with this because we are forcing the Poco EntityMode
					clazz = checkPersister.GetMappedClass(EntityMode.Poco);
				}

				if (clazz == null)
				{
					try
					{
						clazz = ReflectHelper.ClassForFullName(className);
					}
					catch (Exception)
					{
						clazz = null;
					}
				}
			}

			if (clazz == null)
			{
				return new[] {className}; //for a dynamic-class
			}

			List<string> results = new List<string>();
			foreach (IEntityPersister p in entityPersisters.Values)
			{
				IQueryable q = p as IQueryable;
				if (q != null)
				{
					string testClassName = q.EntityName;
					bool isMappedClass = className.Equals(testClassName);
					if (q.IsExplicitPolymorphism)
					{
						if (isMappedClass)
						{
							return new string[] {testClassName}; // NOTE EARLY EXIT
						}
					}
					else
					{
						if (isMappedClass)
						{
							results.Add(testClassName);
						}
						else
						{
							System.Type mappedClass = q.GetMappedClass(EntityMode.Poco);
							if (mappedClass != null && clazz.IsAssignableFrom(mappedClass))
							{
								bool assignableSuperclass;
								if (q.IsInherited)
								{
									System.Type mappedSuperclass = GetEntityPersister(q.MappedSuperclass).GetMappedClass(EntityMode.Poco);
									assignableSuperclass = clazz.IsAssignableFrom(mappedSuperclass);
								}
								else
								{
									assignableSuperclass = false;
								}
								if (!assignableSuperclass)
								{
									results.Add(testClassName);
								}
							}
						}
					}
				}
			}
			return results.ToArray();
		}
        private void UpdateWardList(List<Ward> wardList, FormCollection model, string key)
        {
            var wardCounter = Convert.ToInt32(key.Substring(key.IndexOf("_", StringComparison.CurrentCultureIgnoreCase) + 1));
            if (wardList.Count < wardCounter)
            {
                wardList.Add(new Ward());
            }

            var ward = wardList[wardCounter - 1];
            switch(key.Substring(0,key.IndexOf("_", StringComparison.CurrentCultureIgnoreCase)))
            {
                case "wardMemberId":
                    ward.MemberId = Convert.ToInt32(model[key]);
                    break;
                    case "wardLastname":
                    ward.Lastname = model[key];
                    break;
                    case "wardFirstname":
                    ward.Firstname = model[key];
                    break;
                    case "wardNickname":
                    ward.Nickname = model[key];
                    break;
                    case "wardDob":
                    ward.Dob = DateTime.Parse(model[key]);
                    break;
            }
        }
示例#14
0
        public SearchResults Search(SearchRequest request)
        {
            if (!OpenReader())
            {
                return new SearchResults { Query = request.Query };
            }

            if (!reader.IsCurrent())
            {
                reader = reader.Reopen();
            }

            var take = request.Take > 0 ? request.Take : SearchModuleConstants.DefaultSearchResultsCount;
            var skip = request.Skip > 0 ? request.Skip : 0;

            var result = new List<SearchResultItem>();
            TopScoreDocCollector collector = TopScoreDocCollector.Create(take + skip, true);
            using (var searcher = new IndexSearcher(reader))
            {
                var searchQuery = request.Query;
                Query query;
                try
                {
                    query = parser.Parse(searchQuery);
                }
                catch (ParseException)
                {
                    try
                    {
                        searchQuery = QueryParser.Escape(searchQuery);
                        query = parser.Parse(searchQuery);
                    }
                    catch (ParseException exc)
                    {
                        throw new ValidationException(() => exc.Message, exc.Message, exc);
                    }
                }

                Filter isPublishedFilter = null;
                if (!RetrieveUnpublishedPages())
                {
                    var isPublishedQuery = new TermQuery(new Term(LuceneIndexDocumentKeys.IsPublished, "true"));
                    isPublishedFilter = new QueryWrapperFilter(isPublishedQuery);
                }

                if (LuceneSearchHelper.Search != null)
                {
                    collector = LuceneSearchHelper.Search(query, isPublishedFilter, collector);
                }
                else
                {
                    query = LuceneEvents.Instance.OnSearchQueryExecuting(query, searchQuery).Query;

                    if (isPublishedFilter != null)
                    {
                        // Exclude unpublished pages
                        searcher.Search(query, isPublishedFilter, collector);
                    }
                    else
                    {
                        // Search within all the pages
                        searcher.Search(query, collector);
                    }
                }

                ScoreDoc[] hits = collector.TopDocs(skip, take).ScoreDocs;
                List<Document> hitDocuments = new List<Document>();
                for (int i = 0; i < hits.Length; i++)
                {
                    int docId = hits[i].Doc;
                    Document d = searcher.Doc(docId);
                    hitDocuments.Add(d);
                    result.Add(
                        new SearchResultItem
                        {
                            FormattedUrl = d.Get(LuceneIndexDocumentKeys.Path),
                            Link = d.Get(LuceneIndexDocumentKeys.Path),
                            Title = d.Get(LuceneIndexDocumentKeys.Title),
                            Snippet = GetSnippet(d.Get(LuceneIndexDocumentKeys.Content), request.Query)
                        });
                }

                CheckAvailability(result);

                LuceneEvents.Instance.OnSearchResultRetrieving(hitDocuments, result);
            }

            return new SearchResults
                       {
                           Items = result,
                           Query = request.Query,
                           TotalResults = collector.TotalHits
                       };
        }
示例#15
0
        private bool RetrieveUnpublishedPages()
        {
            // Check if user can manage content
            var allRoles = new List<string>(RootModuleConstants.UserRoles.AllRoles);
            if (!string.IsNullOrEmpty(cmsConfiguration.Security.FullAccessRoles))
            {
                allRoles.Add(cmsConfiguration.Security.FullAccessRoles);
            }

            var retrieveUnpublishedPages = securityService.IsAuthorized(RootModuleConstants.UserRoles.MultipleRoles(allRoles.ToArray()));
            return retrieveUnpublishedPages;
        }
		/// <summary>
		/// Constructs the NormalizedEntityPerister for the PersistentClass.
		/// </summary>
		/// <param name="persistentClass">The PersistentClass to create the EntityPersister for.</param>
		/// <param name="cache">The configured <see cref="ICacheConcurrencyStrategy" />.</param>
		/// <param name="factory">The SessionFactory that this EntityPersister will be stored in.</param>
		/// <param name="mapping">The mapping used to retrieve type information.</param>
		public JoinedSubclassEntityPersister(PersistentClass persistentClass, ICacheConcurrencyStrategy cache,
											 ISessionFactoryImplementor factory, IMapping mapping)
			: base(persistentClass, cache, factory)
		{
			#region DISCRIMINATOR

			if (persistentClass.IsPolymorphic)
			{
				try
				{
					discriminatorValue = persistentClass.SubclassId;
					discriminatorSQLString = discriminatorValue.ToString();
				}
				catch (Exception e)
				{
					throw new MappingException("Could not format discriminator value to SQL string", e);
				}
			}
			else
			{
				discriminatorValue = null;
				discriminatorSQLString = null;
			}

			if (OptimisticLockMode > Versioning.OptimisticLock.Version)
				throw new MappingException(string.Format("optimistic-lock=all|dirty not supported for joined-subclass mappings [{0}]", EntityName));

			#endregion

			#region MULTITABLES
			int idColumnSpan = IdentifierColumnSpan;

			List<string> tables = new List<string>();
			List<string[]> keyColumns = new List<string[]>();
			List<bool> cascadeDeletes = new List<bool>();
			IEnumerator<IKeyValue> kiter = persistentClass.KeyClosureIterator.GetEnumerator();
			foreach (Table tab in persistentClass.TableClosureIterator)
			{
				kiter.MoveNext();
				IKeyValue key = kiter.Current;
				string tabname = tab.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
				tables.Add(tabname);

				List<string> keyCols = new List<string>(idColumnSpan);
				IEnumerable<Column> enumerableKCols = new SafetyEnumerable<Column>(key.ColumnIterator);
				foreach (Column kcol in enumerableKCols)
					keyCols.Add(kcol.GetQuotedName(factory.Dialect));

				keyColumns.Add(keyCols.ToArray());
				cascadeDeletes.Add(key.IsCascadeDeleteEnabled && factory.Dialect.SupportsCascadeDelete);				
			}
			naturalOrderTableNames = tables.ToArray();
			naturalOrderTableKeyColumns = keyColumns.ToArray();
			naturalOrderCascadeDeleteEnabled = cascadeDeletes.ToArray();

			List<string> subtables = new List<string>();
			List<bool> isConcretes = new List<bool>();
			keyColumns = new List<string[]>();
			foreach (Table tab in persistentClass.SubclassTableClosureIterator)
			{
				isConcretes.Add(persistentClass.IsClassOrSuperclassTable(tab));
				string tabname = tab.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
				subtables.Add(tabname);
				List<string> key = new List<string>(idColumnSpan);
				foreach (Column column in tab.PrimaryKey.ColumnIterator)
					key.Add(column.GetQuotedName(factory.Dialect));

				keyColumns.Add(key.ToArray());				
			}
			subclassTableNameClosure = subtables.ToArray();
			subclassTableKeyColumnClosure = keyColumns.ToArray();
			isClassOrSuperclassTable = isConcretes.ToArray();

			constraintOrderedTableNames = new string[subclassTableNameClosure.Length];
			constraintOrderedKeyColumnNames = new string[subclassTableNameClosure.Length][];
			int currentPosition = 0;
			for (int i = subclassTableNameClosure.Length - 1; i >= 0; i--, currentPosition++)
			{
				constraintOrderedTableNames[currentPosition] = subclassTableNameClosure[i];
				constraintOrderedKeyColumnNames[currentPosition] = subclassTableKeyColumnClosure[i];
			}

			tableSpan = naturalOrderTableNames.Length;
			tableNames = Reverse(naturalOrderTableNames);
			tableKeyColumns = Reverse(naturalOrderTableKeyColumns);
			Reverse(subclassTableNameClosure, tableSpan);
			Reverse(subclassTableKeyColumnClosure, tableSpan);

			spaces = ArrayHelper.Join(tableNames, persistentClass.SynchronizedTables.ToArray());

			// Custom sql
			customSQLInsert = new SqlString[tableSpan];
			customSQLUpdate = new SqlString[tableSpan];
			customSQLDelete = new SqlString[tableSpan];
			insertCallable = new bool[tableSpan];
			updateCallable = new bool[tableSpan];
			deleteCallable = new bool[tableSpan];
			insertResultCheckStyles = new ExecuteUpdateResultCheckStyle[tableSpan];
			updateResultCheckStyles = new ExecuteUpdateResultCheckStyle[tableSpan];
			deleteResultCheckStyles = new ExecuteUpdateResultCheckStyle[tableSpan];

			PersistentClass pc = persistentClass;
			int jk = tableSpan - 1;
			while (pc != null)
			{
				customSQLInsert[jk] = pc.CustomSQLInsert;
				insertCallable[jk] = customSQLInsert[jk] != null && pc.IsCustomInsertCallable;
				insertResultCheckStyles[jk] = pc.CustomSQLInsertCheckStyle
											  ??
											  ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLInsert[jk], insertCallable[jk]);
				customSQLUpdate[jk] = pc.CustomSQLUpdate;
				updateCallable[jk] = customSQLUpdate[jk] != null && pc.IsCustomUpdateCallable;
				updateResultCheckStyles[jk] = pc.CustomSQLUpdateCheckStyle
											  ??
											  ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLUpdate[jk], updateCallable[jk]);
				customSQLDelete[jk] = pc.CustomSQLDelete;
				deleteCallable[jk] = customSQLDelete[jk] != null && pc.IsCustomDeleteCallable;
				deleteResultCheckStyles[jk] = pc.CustomSQLDeleteCheckStyle
											  ??
											  ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLDelete[jk], deleteCallable[jk]);
				jk--;
				pc = pc.Superclass;
			}
			if (jk != -1)
			{
				throw new AssertionFailure("Tablespan does not match height of joined-subclass hierarchy.");
			}

			#endregion

			#region PROPERTIES

			int hydrateSpan = PropertySpan;
			naturalOrderPropertyTableNumbers = new int[hydrateSpan];
			propertyTableNumbers = new int[hydrateSpan];
			int i2 = 0;
			foreach (Property prop in persistentClass.PropertyClosureIterator)
			{
				string tabname = prop.Value.Table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
				propertyTableNumbers[i2] = GetTableId(tabname, tableNames);
				naturalOrderPropertyTableNumbers[i2] = GetTableId(tabname, naturalOrderTableNames);
				i2++;
			}

			// subclass closure properties
			List<int> columnTableNumbers = new List<int>();
			List<int> formulaTableNumbers = new List<int>();
			List<int> propTableNumbers = new List<int>();
			foreach (Property prop in persistentClass.SubclassPropertyClosureIterator)
			{
				Table tab = prop.Value.Table;
				string tabname = tab.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
				int tabnum = GetTableId(tabname, subclassTableNameClosure);
				propTableNumbers.Add(tabnum);

				foreach (ISelectable thing in prop.ColumnIterator)
				{
					if (thing.IsFormula)
						formulaTableNumbers.Add(tabnum);
					else
						columnTableNumbers.Add(tabnum);
				}
			}

			subclassColumnTableNumberClosure = columnTableNumbers.ToArray();
			subclassPropertyTableNumberClosure = propTableNumbers.ToArray();
			subclassFormulaTableNumberClosure = formulaTableNumbers.ToArray();
			#endregion

			#region SUBCLASSES

			int subclassSpan = persistentClass.SubclassSpan + 1;
			subclassClosure = new string[subclassSpan];
			subclassClosure[subclassSpan - 1] = EntityName;
			if (persistentClass.IsPolymorphic)
			{
				subclassesByDiscriminatorValue[discriminatorValue] = EntityName;
				discriminatorValues = new string[subclassSpan];
				discriminatorValues[subclassSpan - 1] = discriminatorSQLString;
				notNullColumnTableNumbers = new int[subclassSpan];
				int id =
					GetTableId(
						persistentClass.Table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName,
															   factory.Settings.DefaultSchemaName), subclassTableNameClosure);
				notNullColumnTableNumbers[subclassSpan - 1] = id;
				notNullColumnNames = new string[subclassSpan];
				notNullColumnNames[subclassSpan - 1] = subclassTableKeyColumnClosure[id][0]; 
				//( (Column) model.getTable().getPrimaryKey().getColumnIterator().next() ).getName();
			}
			else
			{
				discriminatorValues = null;
				notNullColumnTableNumbers = null;
				notNullColumnNames = null;
			}

			int k2 = 0;
			foreach (Subclass sc in persistentClass.SubclassIterator)
			{
				subclassClosure[k2] = sc.EntityName;
				try
				{
					if (persistentClass.IsPolymorphic)
					{
						// we now use subclass ids that are consistent across all
						// persisters for a class hierarchy, so that the use of 
						// "foo.class = Bar" works in HQL
						int subclassId = sc.SubclassId; //new Integer(k+1);
						subclassesByDiscriminatorValue[subclassId] = sc.EntityName;
						discriminatorValues[k2] = subclassId.ToString();
						int id =
							GetTableId(
								sc.Table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName,
														  factory.Settings.DefaultSchemaName), subclassTableNameClosure);
						notNullColumnTableNumbers[k2] = id;
						notNullColumnNames[k2] = subclassTableKeyColumnClosure[id][0]; 
						//( (Column) sc.getTable().getPrimaryKey().getColumnIterator().next() ).getName();
					}
				}
				catch (Exception e)
				{
					throw new MappingException("Error parsing discriminator value", e);
				}
				k2++;				
			}

			#endregion

			InitLockers();

			InitSubclassPropertyAliasesMap(persistentClass);

			PostConstruct(mapping);
		}
		public EntityMetamodel(PersistentClass persistentClass, ISessionFactoryImplementor sessionFactory)
		{
			this.sessionFactory = sessionFactory;


			name = persistentClass.EntityName;
			rootName = persistentClass.RootClazz.EntityName;
			entityType = TypeFactory.ManyToOne(name);
			type = persistentClass.MappedClass;
			rootType = persistentClass.RootClazz.MappedClass;
			rootTypeAssemblyQualifiedName = rootType == null ? null : rootType.AssemblyQualifiedName;

			identifierProperty = PropertyFactory.BuildIdentifierProperty(persistentClass,
			                                                             sessionFactory.GetIdentifierGenerator(rootName));

			versioned = persistentClass.IsVersioned;

			bool lazyAvailable = persistentClass.HasPocoRepresentation
			                     && FieldInterceptionHelper.IsInstrumented(persistentClass.MappedClass);
			bool hasLazy = false;

			propertySpan = persistentClass.PropertyClosureSpan;
			properties = new StandardProperty[propertySpan];
			List<int> naturalIdNumbers = new List<int>();

			propertyNames = new string[propertySpan];
			propertyTypes = new IType[propertySpan];
			propertyUpdateability = new bool[propertySpan];
			propertyInsertability = new bool[propertySpan];
			insertInclusions = new ValueInclusion[propertySpan];
			updateInclusions = new ValueInclusion[propertySpan];
			nonlazyPropertyUpdateability = new bool[propertySpan];
			propertyCheckability = new bool[propertySpan];
			propertyNullability = new bool[propertySpan];
			propertyVersionability = new bool[propertySpan];
			propertyLaziness = new bool[propertySpan];
			cascadeStyles = new CascadeStyle[propertySpan];

			int i = 0;
			int tempVersionProperty = NoVersionIndex;
			bool foundCascade = false;
			bool foundCollection = false;
			bool foundMutable = false;
			bool foundInsertGeneratedValue = false;
			bool foundUpdateGeneratedValue = false;
			bool foundNonIdentifierPropertyNamedId = false;
			HasPocoRepresentation = persistentClass.HasPocoRepresentation;
			
			// NH: WARNING if we have to disable lazy/unproxy properties we have to do it in the whole process.
			lazy = persistentClass.IsLazy && (!persistentClass.HasPocoRepresentation || !ReflectHelper.IsFinalClass(persistentClass.ProxyInterface));
			lazyAvailable &= lazy; // <== Disable lazy properties if the class is marked with lazy=false

			bool hadLazyProperties = false;
			bool hadNoProxyRelations = false;
			foreach (Mapping.Property prop in persistentClass.PropertyClosureIterator)
			{
				if (prop.IsLazy)
				{
					hadLazyProperties = true;
				}
				if(prop.UnwrapProxy)
				{
					hadNoProxyRelations = true;
				}

				// NH: A lazy property is a simple property marked with lazy=true
				bool islazyProperty = prop.IsLazy && lazyAvailable && (!prop.IsEntityRelation || prop.UnwrapProxy);
				// NH: A Relation (in this case many-to-one or one-to-one) marked as "no-proxy"
				var isUnwrapProxy = prop.UnwrapProxy && lazyAvailable;

				if (islazyProperty || isUnwrapProxy)
				{
					// NH: verify property proxiability
					var getter = prop.GetGetter(persistentClass.MappedClass);
					if (getter.Method == null || getter.Method.IsDefined(typeof(CompilerGeneratedAttribute), false) == false)
					{
						log.ErrorFormat("Lazy or no-proxy property {0}.{1} is not an auto property, which may result in uninitialized property access", persistentClass.EntityName, prop.Name);
					}
				}

				if (prop == persistentClass.Version)
				{
					tempVersionProperty = i;
					properties[i] = PropertyFactory.BuildVersionProperty(prop, islazyProperty);
				}
				else
				{
					properties[i] = PropertyFactory.BuildStandardProperty(prop, islazyProperty);
				}

				if (prop.IsNaturalIdentifier)
				{
					naturalIdNumbers.Add(i);
				}

				if ("id".Equals(prop.Name))
				{
					foundNonIdentifierPropertyNamedId = true;
				}

				if (islazyProperty)
				{
					hasLazy = true;
				}
				if (isUnwrapProxy)
				{
					hasUnwrapProxyForProperties = true;
				}

				propertyLaziness[i] = islazyProperty;

				propertyNames[i] = properties[i].Name;
				propertyTypes[i] = properties[i].Type;
				propertyNullability[i] = properties[i].IsNullable;
				propertyUpdateability[i] = properties[i].IsUpdateable;
				propertyInsertability[i] = properties[i].IsInsertable;
				insertInclusions[i] = DetermineInsertValueGenerationType(prop, properties[i]);
				updateInclusions[i] = DetermineUpdateValueGenerationType(prop, properties[i]);
				propertyVersionability[i] = properties[i].IsVersionable;
				nonlazyPropertyUpdateability[i] = properties[i].IsUpdateable && !islazyProperty;
				propertyCheckability[i] = propertyUpdateability[i]
				                          ||
				                          (propertyTypes[i].IsAssociationType
				                           && ((IAssociationType) propertyTypes[i]).IsAlwaysDirtyChecked);

				cascadeStyles[i] = properties[i].CascadeStyle;

				if (properties[i].IsLazy)
				{
					hasLazy = true;
				}

				if (properties[i].CascadeStyle != CascadeStyle.None)
				{
					foundCascade = true;
				}

				if (IndicatesCollection(properties[i].Type))
				{
					foundCollection = true;
				}

				if (propertyTypes[i].IsMutable && propertyCheckability[i])
				{
					foundMutable = true;
				}

				if (insertInclusions[i] != ValueInclusion.None)
				{
					foundInsertGeneratedValue = true;
				}

				if (updateInclusions[i] != ValueInclusion.None)
				{
					foundUpdateGeneratedValue = true;
				}

				MapPropertyToIndex(prop, i);
				i++;
			}

			if (naturalIdNumbers.Count == 0)
				naturalIdPropertyNumbers = null;
			else
				naturalIdPropertyNumbers = naturalIdNumbers.ToArray();

			hasCascades = foundCascade;
			hasInsertGeneratedValues = foundInsertGeneratedValue;
			hasUpdateGeneratedValues = foundUpdateGeneratedValue;
			hasNonIdentifierPropertyNamedId = foundNonIdentifierPropertyNamedId;

			versionPropertyIndex = tempVersionProperty;
			hasLazyProperties = hasLazy;

			if(hadLazyProperties && !hasLazy)
			{
				log.WarnFormat("Disabled lazy properies fetching for {0} beacuse it does not support lazy at the entity level", name);
			}
			if (hasLazy)
			{
				log.Info("lazy property fetching available for: " + name);
			}

			if(hadNoProxyRelations && !hasUnwrapProxyForProperties)
			{
				log.WarnFormat("Disabled ghost properies fetching for {0} beacuse it does not support lazy at the entity level", name);
			}
			if (hasUnwrapProxyForProperties)
			{
				log.Info("no-proxy property fetching available for: " + name);
			}

			mutable = persistentClass.IsMutable;

			if (!persistentClass.IsAbstract.HasValue)
			{
				// legacy behavior (with no abstract attribute specified)
				isAbstract = persistentClass.HasPocoRepresentation && ReflectHelper.IsAbstractClass(persistentClass.MappedClass);
			}
			else
			{
				isAbstract = persistentClass.IsAbstract.Value;
				if (!isAbstract && persistentClass.HasPocoRepresentation
				    && ReflectHelper.IsAbstractClass(persistentClass.MappedClass))
				{
					log.Warn("entity [" + type.FullName
					         + "] is abstract-class/interface explicitly mapped as non-abstract; be sure to supply entity-names");
				}
			}
			selectBeforeUpdate = persistentClass.SelectBeforeUpdate;
			dynamicUpdate = persistentClass.DynamicUpdate;
			dynamicInsert = persistentClass.DynamicInsert;

			polymorphic = persistentClass.IsPolymorphic;
			explicitPolymorphism = persistentClass.IsExplicitPolymorphism;
			inherited = persistentClass.IsInherited;
			superclass = inherited ? persistentClass.Superclass.EntityName : null;
			superclassType = inherited ? persistentClass.Superclass.MappedClass : null;
			hasSubclasses = persistentClass.HasSubclasses;

			optimisticLockMode = persistentClass.OptimisticLockMode;
			if (optimisticLockMode > Versioning.OptimisticLock.Version && !dynamicUpdate)
			{
				throw new MappingException("optimistic-lock setting requires dynamic-update=\"true\": " + type.FullName);
			}

			hasCollections = foundCollection;
			hasMutableProperties = foundMutable;

			foreach (Subclass obj in persistentClass.SubclassIterator)
			{
				subclassEntityNames.Add(obj.EntityName);
			}
			subclassEntityNames.Add(name);

			tuplizerMapping = new EntityEntityModeToTuplizerMapping(persistentClass, this);
		}
		public UnionSubclassEntityPersister(PersistentClass persistentClass, ICacheConcurrencyStrategy cache, 
			ISessionFactoryImplementor factory, IMapping mapping):base(persistentClass, cache, factory)
		{
			if (IdentifierGenerator is IdentityGenerator)
			{
				throw new MappingException("Cannot use identity column key generation with <union-subclass> mapping for: " + EntityName);
			}

			// TABLE

			tableName =
				persistentClass.Table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName,
				                                       factory.Settings.DefaultSchemaName);

			#region Custom SQL

			SqlString sql;
			bool callable;
			ExecuteUpdateResultCheckStyle checkStyle;

			sql = persistentClass.CustomSQLInsert;
			callable = sql != null && persistentClass.IsCustomInsertCallable;
			checkStyle = sql == null
			             	? ExecuteUpdateResultCheckStyle.Count
			             	: (persistentClass.CustomSQLInsertCheckStyle
			             	   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(sql, callable));
			customSQLInsert = new SqlString[] { sql };
			insertCallable = new bool[] { callable };
			insertResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };

			sql = persistentClass.CustomSQLUpdate;
			callable = sql != null && persistentClass.IsCustomUpdateCallable;
			checkStyle = sql == null
			             	? ExecuteUpdateResultCheckStyle.Count
			             	: (persistentClass.CustomSQLUpdateCheckStyle
			             	   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(sql, callable));
			customSQLUpdate = new SqlString[] { sql };
			updateCallable = new bool[] { callable };
			updateResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };

			sql = persistentClass.CustomSQLDelete;
			callable = sql != null && persistentClass.IsCustomDeleteCallable;
			checkStyle = sql == null
			             	? ExecuteUpdateResultCheckStyle.Count
			             	: (persistentClass.CustomSQLDeleteCheckStyle
			             	   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(sql, callable));
			customSQLDelete = new SqlString[] { sql };
			deleteCallable = new bool[] { callable };
			deleteResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };

			#endregion

			discriminatorValue = persistentClass.SubclassId;
			discriminatorSQLValue = persistentClass.SubclassId.ToString();

			#region PROPERTIES

			int subclassSpan = persistentClass.SubclassSpan + 1;
			subclassClosure = new string[subclassSpan];
			subclassClosure[0] = EntityName;

			#endregion

			#region SUBCLASSES

			subclassByDiscriminatorValue[persistentClass.SubclassId] = persistentClass.EntityName;
			if (persistentClass.IsPolymorphic)
			{
				int k = 1;
				foreach (Subclass sc in persistentClass.SubclassIterator)
				{
					subclassClosure[k++] = sc.EntityName;
					subclassByDiscriminatorValue[sc.SubclassId] = sc.EntityName;
				}
			}

			#endregion

			#region SPACES
			//TODO: i'm not sure, but perhaps we should exclude abstract denormalized tables?

			int spacesSize = 1 + persistentClass.SynchronizedTables.Count;
			spaces = new string[spacesSize];
			spaces[0] = tableName;
			IEnumerator<string> iSyncTab = persistentClass.SynchronizedTables.GetEnumerator();
			for (int i = 1; i < spacesSize; i++)
			{
				iSyncTab.MoveNext();
				spaces[i] = iSyncTab.Current;
			}

			HashedSet<string> subclassTables = new HashedSet<string>();
			foreach (Table table in persistentClass.SubclassTableClosureIterator)
			{
				subclassTables.Add(
					table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName));
			}
			subclassSpaces = new string[subclassTables.Count];
			subclassTables.CopyTo(subclassSpaces, 0);

			subquery = GenerateSubquery(persistentClass, mapping);

			if (IsMultiTable)
			{
				int idColumnSpan = IdentifierColumnSpan;
				List<string> tableNames = new List<string>();
				List<string[]> keyColumns = new List<string[]>();
				if (!IsAbstract)
				{
					tableNames.Add(tableName);
					keyColumns.Add(IdentifierColumnNames);
				}
				foreach (Table tab in persistentClass.SubclassTableClosureIterator)
				{
					if (!tab.IsAbstractUnionTable)
					{
						string _tableName =
							tab.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
						tableNames.Add(_tableName);

						List<string> key = new List<string>(idColumnSpan);
						foreach (Column column in tab.PrimaryKey.ColumnIterator)
							key.Add(column.GetQuotedName(factory.Dialect));

						keyColumns.Add(key.ToArray());
					}					
				}

				constraintOrderedTableNames = tableNames.ToArray();
				constraintOrderedKeyColumnNames = keyColumns.ToArray();
			}
			else
			{
				constraintOrderedTableNames = new string[] { tableName };
				constraintOrderedKeyColumnNames = new string[][] { IdentifierColumnNames };
			}
			#endregion

			InitLockers();

			InitSubclassPropertyAliasesMap(persistentClass);

			PostConstruct(mapping);
		}
示例#19
0
		private void ProcessIndex(XmlElement indexElement, IDictionary<string, Table> tables)
		{
			var tableName = indexElement.GetAttribute("table");
			var columnNames = CollectionUtils.Map(indexElement.GetAttribute("columns").Split(','), (string s) => s.Trim());

			if (string.IsNullOrEmpty(tableName) || columnNames.Count <= 0)
				return;

			// get table by name
			Table table;
			if (!tables.TryGetValue(tableName, out table))
				throw new DdlException(
					string.Format("An additional index refers to a table ({0}) that does not exist.", table.Name),
					null);

			// get columns by name
			var columns = new List<Column>();
			foreach (var columnName in columnNames)
			{
				var column = CollectionUtils.SelectFirst(table.ColumnIterator, col => col.Name == columnName);
				// bug #6994: could be that the index file specifies a column name that does not actually exist, so we need to check for nulls
				if (column == null)
					throw new DdlException(
						string.Format("An additional index on table {0} refers to a column ({1}) that does not exist.", table.Name, columnName),
						null);
				columns.Add(column);
			}

			// create index
			CreateIndex(table, columns);
		}
		protected internal virtual SqlString GenerateLazySelectString()
		{
			if (!entityMetamodel.HasLazyProperties)
				return null;

			HashedSet<int> tableNumbers = new HashedSet<int>();
			List<int> columnNumbers = new List<int>();
			List<int> formulaNumbers = new List<int>();
			for (int i = 0; i < lazyPropertyNames.Length; i++)
			{
				// all this only really needs to consider properties
				// of this class, not its subclasses, but since we
				// are reusing code used for sequential selects, we
				// use the subclass closure
				int propertyNumber = GetSubclassPropertyIndex(lazyPropertyNames[i]);

				int tableNumber = GetSubclassPropertyTableNumber(propertyNumber);
				tableNumbers.Add(tableNumber);

				int[] colNumbers = subclassPropertyColumnNumberClosure[propertyNumber];
				for (int j = 0; j < colNumbers.Length; j++)
				{
					if (colNumbers[j] != -1)
					{
						columnNumbers.Add(colNumbers[j]);
					}
				}
				int[] formNumbers = subclassPropertyFormulaNumberClosure[propertyNumber];
				for (int j = 0; j < formNumbers.Length; j++)
				{
					if (formNumbers[j] != -1)
					{
						formulaNumbers.Add(formNumbers[j]);
					}
				}
			}

			if (columnNumbers.Count == 0 && formulaNumbers.Count == 0)
			{
				// only one-to-one is lazy fetched
				return null;
			}

			return RenderSelect(tableNumbers.ToArray(), columnNumbers.ToArray(), formulaNumbers.ToArray());
		}
        //
        // GET: /Courses/
        public ActionResult Index()
        {
            String contextUserName = User.Identity.Name;
            if (String.IsNullOrEmpty(contextUserName))
            {
                ViewBag.Message = "we couldn't locate your profile";
                return View("Error");
            }
            StudentRecord studentRecord = null;
            List<StudentEnrollmentViewModel> listOfEnrolledCourses = null;
            try
            {
                var enrollmentModel = new StudentEnrollmentsModel();
                studentRecord = enrollmentModel.GetStudentRecord(contextUserName);
                if (studentRecord == null)
                {
                    ViewBag.Message = "our records show that you're not enrolled in any classes..";
                    return View("Error");
                }
                // TO DO:
                // Find a more elegant way to do this
                // probably move it to the service.
                listOfEnrolledCourses = new List<StudentEnrollmentViewModel>();

                foreach (var item in studentRecord.StudentCourseEnrollments)
                {
                    listOfEnrolledCourses.Add(new StudentEnrollmentViewModel
                    {
                        Course = m_contextCoursesService.GetCourse(item.CourseId),
                        EnrollmentInfo = item
                    });
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
                return View("Error");
            }

            return View(listOfEnrolledCourses);
        }
		private SqlString GenerateSequentialSelect(ILoadable persister)
		{
			//note that this method could easily be moved up to BasicEntityPersister,
			//if we ever needed to reuse it from other subclasses

			//figure out which tables need to be fetched
			AbstractEntityPersister subclassPersister = (AbstractEntityPersister)persister;
			HashedSet<int> tableNumbers = new HashedSet<int>();
			string[] props = subclassPersister.PropertyNames;
			string[] classes = subclassPersister.PropertySubclassNames;
			for (int i = 0; i < props.Length; i++)
			{
				int propTableNumber = GetSubclassPropertyTableNumber(props[i], classes[i]);
				if (IsSubclassTableSequentialSelect(propTableNumber) && !IsSubclassTableLazy(propTableNumber))
				{
					tableNumbers.Add(propTableNumber);
				}
			}
			if ((tableNumbers.Count == 0))
				return null;

			//figure out which columns are needed
			List<int> columnNumbers = new List<int>();
			int[] columnTableNumbers = SubclassColumnTableNumberClosure;
			for (int i = 0; i < SubclassColumnClosure.Length; i++)
			{
				if (tableNumbers.Contains(columnTableNumbers[i]))
					columnNumbers.Add(i);
			}

			//figure out which formulas are needed
			List<int> formulaNumbers = new List<int>();
			int[] formulaTableNumbers = SubclassColumnTableNumberClosure;
			for (int i = 0; i < SubclassFormulaTemplateClosure.Length; i++)
			{
				if (tableNumbers.Contains(formulaTableNumbers[i]))
					formulaNumbers.Add(i);
			}

			//render the SQL
			return RenderSelect(ArrayHelper.ToIntArray(tableNumbers), columnNumbers.ToArray(), formulaNumbers.ToArray());
		}
        /// <summary>
        /// Make data property metadata for the entity
        /// </summary>
        /// <param name="propName">name of the property on the server</param>
        /// <param name="typeName">data type of the property, e.g. Int32</param>
        /// <param name="isNullable">whether the property is nullable in the database</param>
        /// <param name="col">Column object, used for maxLength and defaultValue</param>
        /// <param name="isKey">true if this property is part of the key for the entity</param>
        /// <param name="isVersion">true if this property contains the version of the entity (for a concurrency strategy)</param>
        /// <returns></returns>
        private Dictionary<string, object> MakeDataProperty(string propName, string typeName, bool isNullable, Column col, bool isKey, bool isVersion)
        {
            string newType;
            typeName = (BreezeTypeMap.TryGetValue(typeName, out newType)) ? newType : typeName;

            var dmap = new Dictionary<string, object>();
            dmap.Add("nameOnServer", propName);
            dmap.Add("dataType", typeName);
            dmap.Add("isNullable", isNullable);

            if (col != null && col.DefaultValue != null)
            {
                dmap.Add("defaultValue", col.DefaultValue);
            }
            if (isKey)
            {
                dmap.Add("isPartOfKey", true);
            }
            if (isVersion)
            {
                dmap.Add("concurrencyMode", "Fixed");
            }

            var validators = new List<Dictionary<string, string>>();

            if (!isNullable)
            {
                validators.Add(new Dictionary<string, string>() {
                    {"name", "required" },
                });
            }
            if (col != null && col.IsLengthDefined())
            {
                dmap.Add("maxLength", col.Length);

                validators.Add(new Dictionary<string, string>() {
                    {"maxLength", col.Length.ToString() },
                    {"name", "maxLength" }
                });
            }

            string validationType;
            if (ValidationTypeMap.TryGetValue(typeName, out validationType))
            {
                validators.Add(new Dictionary<string, string>() {
                    {"name", validationType },
                });
            }

            if (validators.Any())
                dmap.Add("validators", validators);

            return dmap;
        }
        /// <summary>
        /// Add the properties for an entity.
        /// </summary>
        /// <param name="meta"></param>
        /// <param name="pClass"></param>
        /// <param name="dataList">will be populated with the data properties of the entity</param>
        /// <param name="navList">will be populated with the navigation properties of the entity</param>
        void AddClassProperties(IClassMetadata meta, PersistentClass pClass, List<Dictionary<string, object>> dataList, List<Dictionary<string, object>> navList)
        {
            // maps column names to their related data properties.  Used in MakeAssociationProperty to convert FK column names to entity property names.
            var relatedDataPropertyMap = new Dictionary<string, Dictionary<string, object>>();

            var persister = meta as AbstractEntityPersister;
            var type = pClass.MappedClass;

            var propNames = meta.PropertyNames;
            var propTypes = meta.PropertyTypes;
            var propNull = meta.PropertyNullability;
            for (int i = 0; i < propNames.Length; i++)
            {
                var propName = propNames[i];
                var pClassProp = pClass.GetProperty(propName);
                if (!hasOwnProperty(pClass, pClassProp)) continue;  // skip property defined on superclass

                var propType = propTypes[i];
                if (!propType.IsAssociationType)    // skip association types until we handle all the data types, so the relatedDataPropertyMap will be populated.
                {
                    var propColumns = pClassProp.ColumnIterator.ToList();
                    if (propType.IsComponentType)
                    {
                        // complex type
                        var compType = (ComponentType)propType;
                        var complexTypeName = AddComponent(compType, propColumns);
                        var compMap = new Dictionary<string, object>();
                        compMap.Add("nameOnServer", propName);
                        compMap.Add("complexTypeName", complexTypeName);
                        compMap.Add("isNullable", propNull[i]);
                        dataList.Add(compMap);
                    }
                    else
                    {
                        // data property
                        var col = propColumns.Count() == 1 ? propColumns[0] as Column : null;
                        var isKey = meta.HasNaturalIdentifier && meta.NaturalIdentifierProperties.Contains(i);
                        var isVersion = meta.IsVersioned && i == meta.VersionProperty;

                        var dmap = MakeDataProperty(propName, propType.Name, propNull[i], col, isKey, isVersion);
                        dataList.Add(dmap);

                        var columnNameString = GetPropertyColumnNames(persister, propName); 
                        relatedDataPropertyMap.Add(columnNameString, dmap);
                    }
                }
            }


            // Hibernate identifiers are excluded from the list of data properties, so we have to add them separately
            if (meta.HasIdentifierProperty && hasOwnProperty(pClass, meta.IdentifierPropertyName))
            {
                var dmap = MakeDataProperty(meta.IdentifierPropertyName, meta.IdentifierType.Name, false, null, true, false);
                dataList.Insert(0, dmap);

                var columnNameString = GetPropertyColumnNames(persister, meta.IdentifierPropertyName);
                relatedDataPropertyMap.Add(columnNameString, dmap);
            }
            else if (meta.IdentifierType != null && meta.IdentifierType.IsComponentType 
                && pClass.Identifier is Component && ((Component)pClass.Identifier).Owner == pClass)
            {
                // composite key is a ComponentType
                var compType = (ComponentType)meta.IdentifierType;
                var compNames = compType.PropertyNames;
                for (int i = 0; i < compNames.Length; i++)
                {
                    var compName = compNames[i];

                    var propType = compType.Subtypes[i];
                    if (!propType.IsAssociationType)
                    {
                        var dmap = MakeDataProperty(compName, propType.Name, compType.PropertyNullability[i], null, true, false);
                        dataList.Insert(0, dmap);
                    }
                    else
                    {
                        var manyToOne = propType as ManyToOneType;
                        //var joinable = manyToOne.GetAssociatedJoinable(this._sessionFactory);
                        var propColumnNames = GetPropertyColumnNames(persister, compName);

                        var assProp = MakeAssociationProperty(type, (IAssociationType)propType, compName, propColumnNames, pClass, relatedDataPropertyMap, true);
                        navList.Add(assProp);
                    }
                }
            }

            // We do the association properties after the data properties, so we can do the foreign key lookups
            for (int i = 0; i < propNames.Length; i++)
            {
                var propName = propNames[i];
                if (!hasOwnProperty(pClass, propName)) continue;  // skip property defined on superclass 

                var propType = propTypes[i];
                if (propType.IsAssociationType)
                {
                    // navigation property
                    var propColumnNames = GetPropertyColumnNames(persister, propName);
                    var assProp = MakeAssociationProperty(type, (IAssociationType)propType, propName, propColumnNames, pClass, relatedDataPropertyMap, false);
                    navList.Add(assProp);
                }
            }
        }
		public SingleTableEntityPersister(PersistentClass persistentClass, ICacheConcurrencyStrategy cache,
																			ISessionFactoryImplementor factory, IMapping mapping)
			: base(persistentClass, cache, factory)
		{
			#region CLASS + TABLE

			joinSpan = persistentClass.JoinClosureSpan + 1;
			qualifiedTableNames = new string[joinSpan];
			isInverseTable = new bool[joinSpan];
			isNullableTable = new bool[joinSpan];
			keyColumnNames = new string[joinSpan][];
			Table table = persistentClass.RootTable;
			qualifiedTableNames[0] =
				table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
			isInverseTable[0] = false;
			isNullableTable[0] = false;
			keyColumnNames[0] = IdentifierColumnNames;
			cascadeDeleteEnabled = new bool[joinSpan];

			// Custom sql
			customSQLInsert = new SqlString[joinSpan];
			customSQLUpdate = new SqlString[joinSpan];
			customSQLDelete = new SqlString[joinSpan];
			insertCallable = new bool[joinSpan];
			updateCallable = new bool[joinSpan];
			deleteCallable = new bool[joinSpan];
			insertResultCheckStyles = new ExecuteUpdateResultCheckStyle[joinSpan];
			updateResultCheckStyles = new ExecuteUpdateResultCheckStyle[joinSpan];
			deleteResultCheckStyles = new ExecuteUpdateResultCheckStyle[joinSpan];

			customSQLInsert[0] = persistentClass.CustomSQLInsert;
			insertCallable[0] = customSQLInsert[0] != null && persistentClass.IsCustomInsertCallable;
			insertResultCheckStyles[0] = persistentClass.CustomSQLInsertCheckStyle
																	 ?? ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLInsert[0], insertCallable[0]);
			customSQLUpdate[0] = persistentClass.CustomSQLUpdate;
			updateCallable[0] = customSQLUpdate[0] != null && persistentClass.IsCustomUpdateCallable;
			updateResultCheckStyles[0] = persistentClass.CustomSQLUpdateCheckStyle
																	 ?? ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLUpdate[0], updateCallable[0]);
			customSQLDelete[0] = persistentClass.CustomSQLDelete;
			deleteCallable[0] = customSQLDelete[0] != null && persistentClass.IsCustomDeleteCallable;
			deleteResultCheckStyles[0] = persistentClass.CustomSQLDeleteCheckStyle
																	 ?? ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLDelete[0], deleteCallable[0]);

			#endregion

			#region JOINS
			int j = 1;
			foreach (Join join in persistentClass.JoinClosureIterator)
			{
				qualifiedTableNames[j] = join.Table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
				isInverseTable[j] = join.IsInverse;
				isNullableTable[j] = join.IsOptional;
				cascadeDeleteEnabled[j] = join.Key.IsCascadeDeleteEnabled && factory.Dialect.SupportsCascadeDelete;

				customSQLInsert[j] = join.CustomSQLInsert;
				insertCallable[j] = customSQLInsert[j] != null && join.IsCustomInsertCallable;
				insertResultCheckStyles[j] = join.CustomSQLInsertCheckStyle
																		 ??
																		 ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLInsert[j], insertCallable[j]);
				customSQLUpdate[j] = join.CustomSQLUpdate;
				updateCallable[j] = customSQLUpdate[j] != null && join.IsCustomUpdateCallable;
				updateResultCheckStyles[j] = join.CustomSQLUpdateCheckStyle
																		 ??
																		 ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLUpdate[j], updateCallable[j]);
				customSQLDelete[j] = join.CustomSQLDelete;
				deleteCallable[j] = customSQLDelete[j] != null && join.IsCustomDeleteCallable;
				deleteResultCheckStyles[j] = join.CustomSQLDeleteCheckStyle
																		 ??
																		 ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLDelete[j], deleteCallable[j]);

				IEnumerable<Column> enumerableKeyCol = new SafetyEnumerable<Column>(join.Key.ColumnIterator);
				List<string> kcName = new List<string>(join.Key.ColumnSpan);
				foreach (Column col in enumerableKeyCol)
					kcName.Add(col.GetQuotedName(factory.Dialect));

				keyColumnNames[j] = kcName.ToArray();

				j++;
			}

			constraintOrderedTableNames = new string[qualifiedTableNames.Length];
			constraintOrderedKeyColumnNames = new string[qualifiedTableNames.Length][];
			for (int i = qualifiedTableNames.Length - 1, position = 0; i >= 0; i--, position++)
			{
				constraintOrderedTableNames[position] = qualifiedTableNames[i];
				constraintOrderedKeyColumnNames[position] = keyColumnNames[i];
			}

			spaces = ArrayHelper.Join(qualifiedTableNames, ArrayHelper.ToStringArray(persistentClass.SynchronizedTables));

			bool lazyAvailable = IsInstrumented(EntityMode.Poco);

			bool hasDeferred = false;
			List<string> subclassTables = new List<string>();
			List<string[]> joinKeyColumns = new List<string[]>();
			List<bool> isConcretes = new List<bool>();
			List<bool> isDeferreds = new List<bool>();
			List<bool> isInverses = new List<bool>();
			List<bool> isNullables = new List<bool>();
			List<bool> isLazies = new List<bool>();
			subclassTables.Add(qualifiedTableNames[0]);
			joinKeyColumns.Add(IdentifierColumnNames);
			isConcretes.Add(true);
			isDeferreds.Add(false);
			isInverses.Add(false);
			isNullables.Add(false);
			isLazies.Add(false);
			foreach (Join join in persistentClass.SubclassJoinClosureIterator)
			{
				isConcretes.Add(persistentClass.IsClassOrSuperclassJoin(join));
				isDeferreds.Add(join.IsSequentialSelect);
				isInverses.Add(join.IsInverse);
				isNullables.Add(join.IsOptional);
				isLazies.Add(lazyAvailable && join.IsLazy);
				if (join.IsSequentialSelect && !persistentClass.IsClassOrSuperclassJoin(join))
					hasDeferred = true;
				subclassTables.Add(join.Table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName));
				IEnumerable<Column> enumerableKeyCol = new SafetyEnumerable<Column>(join.Key.ColumnIterator);
				List<string> keyCols = new List<string>(join.Key.ColumnSpan);
				foreach (Column col in enumerableKeyCol)
					keyCols.Add(col.GetQuotedName(factory.Dialect));

				joinKeyColumns.Add(keyCols.ToArray());
			}

			subclassTableSequentialSelect = isDeferreds.ToArray();
			subclassTableNameClosure = subclassTables.ToArray();
			subclassTableIsLazyClosure = isLazies.ToArray();
			subclassTableKeyColumnClosure = joinKeyColumns.ToArray();
			isClassOrSuperclassTable = isConcretes.ToArray();
			isInverseSubclassTable = isInverses.ToArray();
			isNullableSubclassTable = isNullables.ToArray();
			hasSequentialSelects = hasDeferred;

			#endregion

			#region DISCRIMINATOR

			if (persistentClass.IsPolymorphic)
			{
				IValue discrimValue = persistentClass.Discriminator;
				if (discrimValue == null)
					throw new MappingException("Discriminator mapping required for single table polymorphic persistence");

				forceDiscriminator = persistentClass.IsForceDiscriminator;
				IEnumerator<ISelectable> iSel = discrimValue.ColumnIterator.GetEnumerator();
				iSel.MoveNext();
				ISelectable selectable = iSel.Current;
				if (discrimValue.HasFormula)
				{
					Formula formula = (Formula)selectable;
					discriminatorFormula = formula.FormulaString;
					discriminatorFormulaTemplate = formula.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
					discriminatorColumnName = null;
					discriminatorAlias = Discriminator_Alias;
				}
				else
				{
					Column column = (Column)selectable;
					discriminatorColumnName = column.GetQuotedName(factory.Dialect);
					discriminatorAlias = column.GetAlias(factory.Dialect, persistentClass.RootTable);
					discriminatorFormula = null;
					discriminatorFormulaTemplate = null;
				}
				discriminatorType = persistentClass.Discriminator.Type;
				if (persistentClass.IsDiscriminatorValueNull)
				{
					discriminatorValue = NullDiscriminator;
					discriminatorSQLValue = InFragment.Null;
					discriminatorInsertable = false;
				}
				else if (persistentClass.IsDiscriminatorValueNotNull)
				{
					discriminatorValue = NotNullDiscriminator;
					discriminatorSQLValue = InFragment.NotNull;
					discriminatorInsertable = false;
				}
				else
				{
					discriminatorInsertable = persistentClass.IsDiscriminatorInsertable && !discrimValue.HasFormula;
					try
					{
						IDiscriminatorType dtype = (IDiscriminatorType)discriminatorType;
						discriminatorValue = dtype.StringToObject(persistentClass.DiscriminatorValue);
						discriminatorSQLValue = dtype.ObjectToSQLString(discriminatorValue, factory.Dialect);
					}
					catch (InvalidCastException cce)
					{
						throw new MappingException(
							string.Format("Illegal discriminator type: {0} of entity {1}", discriminatorType.Name, persistentClass.EntityName), cce);
					}
					catch (Exception e)
					{
						throw new MappingException("Could not format discriminator value to SQL string of entity " + persistentClass.EntityName, e);
					}
				}
			}
			else
			{
				forceDiscriminator = false;
				discriminatorInsertable = false;
				discriminatorColumnName = null;
				discriminatorAlias = null;
				discriminatorType = null;
				discriminatorValue = null;
				discriminatorSQLValue = null;
				discriminatorFormula = null;
				discriminatorFormulaTemplate = null;
			}

			#endregion

			#region PROPERTIES

			propertyTableNumbers = new int[PropertySpan];
			int i2 = 0;
			foreach (Property prop in persistentClass.PropertyClosureIterator)
			{
				propertyTableNumbers[i2++] = persistentClass.GetJoinNumber(prop);
			}

			List<int> columnJoinNumbers = new List<int>();
			List<int> formulaJoinedNumbers = new List<int>();
			List<int> propertyJoinNumbers = new List<int>();
			foreach (Property prop in persistentClass.SubclassPropertyClosureIterator)
			{
				int join = persistentClass.GetJoinNumber(prop);
				propertyJoinNumbers.Add(join);

				//propertyTableNumbersByName.put( prop.getName(), join );
				propertyTableNumbersByNameAndSubclass[prop.PersistentClass.EntityName + '.' + prop.Name] = join;
				foreach (ISelectable thing in prop.ColumnIterator)
				{
					if (thing.IsFormula)
						formulaJoinedNumbers.Add(join);
					else
						columnJoinNumbers.Add(join);
				}
			}

			subclassColumnTableNumberClosure = columnJoinNumbers.ToArray();
			subclassFormulaTableNumberClosure = formulaJoinedNumbers.ToArray();
			subclassPropertyTableNumberClosure = propertyJoinNumbers.ToArray();

			int subclassSpan = persistentClass.SubclassSpan + 1;
			subclassClosure = new string[subclassSpan];
			subclassClosure[0] = EntityName;
			if (persistentClass.IsPolymorphic)
				subclassesByDiscriminatorValue[discriminatorValue] = EntityName;

			#endregion

			#region SUBCLASSES
			if (persistentClass.IsPolymorphic)
			{
				int k = 1;
				foreach (Subclass sc in persistentClass.SubclassIterator)
				{
					subclassClosure[k++] = sc.EntityName;
					if (sc.IsDiscriminatorValueNull)
					{
						subclassesByDiscriminatorValue[NullDiscriminator] = sc.EntityName;
					}
					else if (sc.IsDiscriminatorValueNotNull)
					{
						subclassesByDiscriminatorValue[NotNullDiscriminator] = sc.EntityName;
					}
					else
					{
						if (discriminatorType == null)
							throw new MappingException("Not available discriminator type of entity " + persistentClass.EntityName);
						try
						{
							IDiscriminatorType dtype = (IDiscriminatorType)discriminatorType;
							subclassesByDiscriminatorValue[dtype.StringToObject(sc.DiscriminatorValue)] = sc.EntityName;
						}
						catch (InvalidCastException cce)
						{
							throw new MappingException(
								string.Format("Illegal discriminator type: {0} of entity {1}", discriminatorType.Name, persistentClass.EntityName), cce);
						}
						catch (Exception e)
						{
							throw new MappingException("Error parsing discriminator value of entity " + persistentClass.EntityName, e);
						}
					}
				}
			}

			#endregion

			InitLockers();

			InitSubclassPropertyAliasesMap(persistentClass);

			PostConstruct(mapping);
		}
示例#26
0
        /// <summary>
        /// Add the properties for an entity.
        /// </summary>
        /// <param name="meta"></param>
        /// <param name="pClass"></param>
        /// <param name="dataList">will be populated with the data properties of the entity</param>
        /// <param name="navList">will be populated with the navigation properties of the entity</param>
        void AddClassProperties(IClassMetadata meta, PersistentClass pClass, List<Dictionary<string, object>> dataList, List<Dictionary<string, object>> navList)
        {
            // Hibernate identifiers are excluded from the list of data properties, so we have to add them separately
            if (meta.HasIdentifierProperty)
            {
                var dmap = MakeDataProperty(meta.IdentifierPropertyName, meta.IdentifierType.Name, false, null, true, false);
                dataList.Add(dmap);
            }
            else if (meta.IdentifierType != null && meta.IdentifierType.IsComponentType)
            {
                // composite key is a ComponentType
                var compType = (ComponentType) meta.IdentifierType;
                var compNames = compType.PropertyNames;
                for (int i = 0; i < compNames.Length; i++)
                {
                    var dmap = MakeDataProperty(compNames[i], compType.Subtypes[i].Name, compType.PropertyNullability[i], null, true, false);
                    dataList.Add(dmap);
                }
            }

            var propNames = meta.PropertyNames;
            var propTypes = meta.PropertyTypes;
            var propNull = meta.PropertyNullability;
            for (int i = 0; i < propNames.Length; i++)
            {
                var propType = propTypes[i];
                var propName = propNames[i];
                var propColumns = pClass.GetProperty(propName).ColumnIterator.ToList();
                if (propType.IsAssociationType)
                {
                    // navigation property
                    var atype = (IAssociationType)propType;
                    var nmap = new Dictionary<string, object>();
                    navList.Add(nmap);
                    nmap.Add("nameOnServer", propName);

                    var entityType = GetEntityType(propType.ReturnedClass, propType.IsCollectionType);
                    nmap.Add("entityTypeName", entityType.Name + ":#" + entityType.Namespace);
                    nmap.Add("isScalar", !propType.IsCollectionType);

                    // the associationName must be the same at both ends of the association.
                    nmap.Add("associationName", GetAssociationName(pClass.MappedClass.Name, entityType.Name, (atype is OneToOneType)));

                    // The foreign key columns usually applies for many-to-one associations
                    IList<string> fks = null;
                    if (propColumns.Any())
                    {
                        fks = propColumns.Select(c => c.Text).ToList();
                        nmap.Add("foreignKeyNamesOnServer", fks);
                    }
                }
                else if (propType.IsComponentType)
                {
                    // complex type
                    var compType = (ComponentType)propType;
                    var complexTypeName = AddComponent(compType, propColumns);
                    var compMap = new Dictionary<string, object>();
                    compMap.Add("nameOnServer", propName);
                    compMap.Add("complexTypeName", complexTypeName);
                    compMap.Add("isNullable", propNull[i]);
                    dataList.Add(compMap);
                }
                else
                {
                    // data property
                    var col = propColumns.Count() == 1 ? propColumns[0] as Column : null;
                    var isKey = meta.HasNaturalIdentifier && meta.NaturalIdentifierProperties.Contains(i);
                    var isVersion = meta.IsVersioned && i == meta.VersionProperty;

                    var dmap = MakeDataProperty(propName, propType.Name, propNull[i], col, isKey, isVersion);
                    dataList.Add(dmap);
                }
                // TODO add validators to the property.
            }
        }
示例#27
0
		public EntityMetamodel(PersistentClass persistentClass, ISessionFactoryImplementor sessionFactory)
		{
			this.sessionFactory = sessionFactory;


			name = persistentClass.EntityName;
			rootName = persistentClass.RootClazz.EntityName;
			entityType = TypeFactory.ManyToOne(name);
			type = persistentClass.MappedClass;
			rootType = persistentClass.RootClazz.MappedClass;
			rootTypeAssemblyQualifiedName = rootType.AssemblyQualifiedName;

			identifierProperty =
				PropertyFactory.BuildIdentifierProperty(persistentClass, sessionFactory.GetIdentifierGenerator(rootType));

			versioned = persistentClass.IsVersioned;

			bool lazyAvailable = persistentClass.HasPocoRepresentation && FieldInterceptionHelper.IsInstrumented(persistentClass.MappedClass);
			bool hasLazy = false;

			propertySpan = persistentClass.PropertyClosureSpan;
			properties = new StandardProperty[propertySpan];
			List<int> naturalIdNumbers = new List<int>();

			#region temporary

			propertyNames = new string[propertySpan];
			propertyTypes = new IType[propertySpan];
			propertyUpdateability = new bool[propertySpan];
			propertyInsertability = new bool[propertySpan];
			insertInclusions = new ValueInclusion[propertySpan];
			updateInclusions = new ValueInclusion[propertySpan];
			nonlazyPropertyUpdateability = new bool[propertySpan];
			propertyCheckability = new bool[propertySpan];
			propertyNullability = new bool[propertySpan];
			propertyVersionability = new bool[propertySpan];
			propertyLaziness = new bool[propertySpan];
			cascadeStyles = new CascadeStyle[propertySpan];

			#endregion


			int i = 0;
			int tempVersionProperty = NoVersionIndex;
			bool foundCascade = false;
			bool foundCollection = false;
			bool foundMutable = false;
			bool foundInsertGeneratedValue = false;
			bool foundUpdateGeneratedValue = false;
			bool foundNonIdentifierPropertyNamedId = false;

			foreach (Mapping.Property prop in persistentClass.PropertyClosureIterator)
			{
				if (prop == persistentClass.Version)
				{
					tempVersionProperty = i;
					properties[i] = PropertyFactory.BuildVersionProperty(prop, lazyAvailable);
				}
				else
				{
					properties[i] = PropertyFactory.BuildStandardProperty(prop, lazyAvailable);
				}

				if (prop.IsNaturalIdentifier)
				{
					naturalIdNumbers.Add(i);
				}

				if ("id".Equals(prop.Name))
				{
					foundNonIdentifierPropertyNamedId = true;
				}

				#region temporary
				bool lazyProperty = prop.IsLazy && lazyAvailable;
				if (lazyProperty)
					hasLazy = true;
				propertyLaziness[i] = lazyProperty;

				propertyNames[i] = properties[i].Name;
				propertyTypes[i] = properties[i].Type;
				propertyNullability[i] = properties[i].IsNullable;
				propertyUpdateability[i] = properties[i].IsUpdateable;
				propertyInsertability[i] = properties[i].IsInsertable;
				insertInclusions[i] = DetermineInsertValueGenerationType(prop, properties[i]);
				updateInclusions[i] = DetermineUpdateValueGenerationType(prop, properties[i]);
				propertyVersionability[i] = properties[i].IsVersionable;
				nonlazyPropertyUpdateability[i] = properties[i].IsUpdateable && !lazyProperty;
				propertyCheckability[i] = propertyUpdateability[i] ||
				                          (propertyTypes[i].IsAssociationType &&
				                           ((IAssociationType) propertyTypes[i]).IsAlwaysDirtyChecked);

				cascadeStyles[i] = properties[i].CascadeStyle;
				#endregion

				if (properties[i].IsLazy)
				{
					hasLazy = true;
				}

				if (properties[i].CascadeStyle != CascadeStyle.None)
				{
					foundCascade = true;
				}

				if (IndicatesCollection(properties[i].Type))
				{
					foundCollection = true;
				}

				if (propertyTypes[i].IsMutable && propertyCheckability[i])
				{
					foundMutable = true;
				}

				if (insertInclusions[i] != ValueInclusion.None)
				{
					foundInsertGeneratedValue = true;
				}

				if (updateInclusions[i] != ValueInclusion.None)
				{
					foundUpdateGeneratedValue = true;
				}

				MapPropertyToIndex(prop, i);
				i++;
			}

			if (naturalIdNumbers.Count == 0)
				naturalIdPropertyNumbers = null;
			else
				naturalIdPropertyNumbers = naturalIdNumbers.ToArray();

			hasCascades = foundCascade;
			hasInsertGeneratedValues = foundInsertGeneratedValue;
			hasUpdateGeneratedValues = foundUpdateGeneratedValue;
			hasNonIdentifierPropertyNamedId = foundNonIdentifierPropertyNamedId;

			versionPropertyIndex = tempVersionProperty;
			hasLazyProperties = hasLazy;
			if (hasLazyProperties) log.Info("lazy property fetching available for: " + name);

			lazy = persistentClass.IsLazy && 
				(!persistentClass.HasPocoRepresentation || !ReflectHelper.IsFinalClass(persistentClass.ProxyInterface));
			mutable = persistentClass.IsMutable;

			if (!persistentClass.IsAbstract.HasValue)
			{
				// legacy behavior (with no abstract attribute specified)
				isAbstract = persistentClass.HasPocoRepresentation &&
				             ReflectHelper.IsAbstractClass(persistentClass.MappedClass);
			}
			else
			{
				isAbstract = persistentClass.IsAbstract.Value;
				if (!isAbstract && persistentClass.HasPocoRepresentation &&
				    ReflectHelper.IsAbstractClass(persistentClass.MappedClass))
				{
					log.Warn("entity [" + type.FullName +
					         "] is abstract-class/interface explicitly mapped as non-abstract; be sure to supply entity-names");
				}
			}
			selectBeforeUpdate = persistentClass.SelectBeforeUpdate;
			dynamicUpdate = persistentClass.DynamicUpdate;
			dynamicInsert = persistentClass.DynamicInsert;

			polymorphic = persistentClass.IsPolymorphic;
			explicitPolymorphism = persistentClass.IsExplicitPolymorphism;
			inherited = persistentClass.IsInherited;
			superclass = inherited ? persistentClass.Superclass.EntityName : null;
			superclassType = inherited ?
			                           	persistentClass.Superclass.MappedClass :
			                           	                                       	null;
			hasSubclasses = persistentClass.HasSubclasses;

			optimisticLockMode = persistentClass.OptimisticLockMode;
			if (optimisticLockMode > Versioning.OptimisticLock.Version && !dynamicUpdate)
			{
				throw new MappingException("optimistic-lock setting requires dynamic-update=\"true\": " + type.FullName);
			}

			hasCollections = foundCollection;
			hasMutableProperties = foundMutable;

			foreach (Subclass obj in persistentClass.SubclassIterator)
			{
				subclassEntityNames.Add(obj.EntityName);
			}
			subclassEntityNames.Add(name);

			tuplizerMapping = new EntityEntityModeToTuplizerMapping(persistentClass, this);
		}
示例#28
0
        /// <summary>
        /// Adds a complex type definition
        /// </summary>
        /// <param name="compType">The complex type</param>
        /// <param name="propColumns">The columns which the complex type spans.  These are used to get the length and defaultValues</param>
        /// <returns>The class name and namespace in the form "Location:#Breeze.Nhibernate.NorthwindIBModel"</returns>
        string AddComponent(ComponentType compType, List<ISelectable> propColumns)
        {
            var type = compType.ReturnedClass;

            // "Location:#Breeze.Nhibernate.NorthwindIBModel"
            var classKey = type.Name + ":#" + type.Namespace;
            if (_typeNames.Contains(classKey))
            {
                // Only add a complex type definition once.
                return classKey;
            }

            var cmap = new Dictionary<string, object>();
            _typeList.Insert(0, cmap);  // insert, because complex type definitions must come before they are referenced
            _typeNames.Add(classKey);

            cmap.Add("shortName", type.Name);
            cmap.Add("namespace", type.Namespace);
            cmap.Add("isComplexType", true);

            var dataList = new List<Dictionary<string, object>>();
            cmap.Add("dataProperties", dataList);

            var propNames = compType.PropertyNames;
            var propTypes = compType.Subtypes;
            var propNull = compType.PropertyNullability;

            var colIndex = 0;
            for (int i = 0; i < propNames.Length; i++)
            {
                var propType = propTypes[i];
                var propName = propNames[i];
                if (propType.IsComponentType)
                {
                    // complex type
                    var compType2 = (ComponentType)propType;
                    var span = compType2.GetColumnSpan((IMapping) _sessionFactory);
                    var subColumns = propColumns.Skip(colIndex).Take(span).ToList();
                    var complexTypeName = AddComponent(compType2, subColumns);
                    var compMap = new Dictionary<string, object>();
                    compMap.Add("nameOnServer", propName);
                    compMap.Add("complexTypeName", complexTypeName);
                    compMap.Add("isNullable", propNull[i]);
                    dataList.Add(compMap);
                    colIndex += span;
                }
                else
                {
                    // data property
                    var col = propColumns.Count() == 1 ? propColumns[colIndex] as Column : null;
                    var dmap = MakeDataProperty(propName, propType.Name, propNull[i], col, false, false);
                    dataList.Add(dmap);
                    colIndex++;
                }
            }
            return classKey;
        }
		protected AbstractEntityPersister(PersistentClass persistentClass, ICacheConcurrencyStrategy cache,
																			ISessionFactoryImplementor factory)
		{
			this.factory = factory;
			this.cache = cache;
			isLazyPropertiesCacheable = persistentClass.IsLazyPropertiesCacheable;
			cacheEntryStructure = factory.Settings.IsStructuredCacheEntriesEnabled
															? (ICacheEntryStructure)new StructuredCacheEntry(this)
															: (ICacheEntryStructure)new UnstructuredCacheEntry();

			entityMetamodel = new EntityMetamodel(persistentClass, factory);

			if (persistentClass.HasPocoRepresentation)
			{
				//TODO: this is currently specific to pojos, but need to be available for all entity-modes
				foreach (Subclass subclass in persistentClass.SubclassIterator)
				{
					entityNameBySubclass[subclass.MappedClass] = subclass.EntityName;
				}
			}

			batchSize = persistentClass.BatchSize.HasValue ? persistentClass.BatchSize.Value : factory.Settings.DefaultBatchFetchSize;
			hasSubselectLoadableCollections = persistentClass.HasSubselectLoadableCollections;

			propertyMapping = new BasicEntityPropertyMapping(this);

			#region IDENTIFIER

			identifierColumnSpan = persistentClass.Identifier.ColumnSpan;
			rootTableKeyColumnNames = new string[identifierColumnSpan];
			identifierAliases = new string[identifierColumnSpan];

			rowIdName = persistentClass.RootTable.RowId;

			loaderName = persistentClass.LoaderName;

			// TODO NH: Not safe cast to Column
			int i = 0;
			foreach (Column col in persistentClass.Identifier.ColumnIterator)
			{
				rootTableKeyColumnNames[i] = col.GetQuotedName(factory.Dialect);
				identifierAliases[i] = col.GetAlias(factory.Dialect, persistentClass.RootTable);
				i++;
			}

			#endregion

			#region VERSION

			if (persistentClass.IsVersioned)
			{
				foreach (Column col in persistentClass.Version.ColumnIterator)
				{
					versionColumnName = col.GetQuotedName(factory.Dialect);
					break; //only happens once
				}
			}
			else
			{
				versionColumnName = null;
			}

			#endregion

			#region WHERE STRING

			sqlWhereString = !string.IsNullOrEmpty(persistentClass.Where) ? "( " + persistentClass.Where + ") " : null;
			sqlWhereStringTemplate = sqlWhereString == null
																? null
																: Template.RenderWhereStringTemplate(sqlWhereString, factory.Dialect,
																																		 factory.SQLFunctionRegistry);

			#endregion

			#region PROPERTIES

			// NH: see consistence with the implementation on EntityMetamodel where we are disabling lazy-properties for no lazy entities
			bool lazyAvailable = IsInstrumented(EntityMode.Poco) && entityMetamodel.IsLazy;

			int hydrateSpan = entityMetamodel.PropertySpan;
			propertyColumnSpans = new int[hydrateSpan];
			propertySubclassNames = new string[hydrateSpan];
			propertyColumnAliases = new string[hydrateSpan][];
			propertyColumnNames = new string[hydrateSpan][];
			propertyColumnFormulaTemplates = new string[hydrateSpan][];
			propertyUniqueness = new bool[hydrateSpan];
			propertySelectable = new bool[hydrateSpan];
			propertyColumnUpdateable = new bool[hydrateSpan][];
			propertyColumnInsertable = new bool[hydrateSpan][];
			var thisClassProperties = new HashSet<Property>();

			lazyProperties = new HashedSet<string>();
			List<string> lazyNames = new List<string>();
			List<int> lazyNumbers = new List<int>();
			List<IType> lazyTypes = new List<IType>();
			List<string[]> lazyColAliases = new List<string[]>();

			i = 0;
			bool foundFormula = false;
			foreach (Property prop in persistentClass.PropertyClosureIterator)
			{
				thisClassProperties.Add(prop);

				int span = prop.ColumnSpan;
				propertyColumnSpans[i] = span;
				propertySubclassNames[i] = prop.PersistentClass.EntityName;
				string[] colNames = new string[span];
				string[] colAliases = new string[span];
				string[] templates = new string[span];
				int k = 0;
				foreach (ISelectable thing in prop.ColumnIterator)
				{
					colAliases[k] = thing.GetAlias(factory.Dialect, prop.Value.Table);
					if (thing.IsFormula)
					{
						foundFormula = true;
						templates[k] = thing.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
					}
					else
					{
						colNames[k] = thing.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
					}
					k++;
				}
				propertyColumnNames[i] = colNames;
				propertyColumnFormulaTemplates[i] = templates;
				propertyColumnAliases[i] = colAliases;

				if (lazyAvailable && prop.IsLazy)
				{
					lazyProperties.Add(prop.Name);
					lazyNames.Add(prop.Name);
					lazyNumbers.Add(i);
					lazyTypes.Add(prop.Value.Type);
					lazyColAliases.Add(colAliases);
				}

				propertyColumnUpdateable[i] = prop.Value.ColumnUpdateability;
				propertyColumnInsertable[i] = prop.Value.ColumnInsertability;

				propertySelectable[i] = prop.IsSelectable;

				propertyUniqueness[i] = prop.Value.IsAlternateUniqueKey;

				i++;
			}
			hasFormulaProperties = foundFormula;
			lazyPropertyColumnAliases = lazyColAliases.ToArray();
			lazyPropertyNames = lazyNames.ToArray();
			lazyPropertyNumbers = lazyNumbers.ToArray();
			lazyPropertyTypes = lazyTypes.ToArray();

			#endregion

			#region SUBCLASS PROPERTY CLOSURE

			List<string> columns = new List<string>();
			List<bool> columnsLazy = new List<bool>();
			List<string> aliases = new List<string>();
			List<string> formulas = new List<string>();
			List<string> formulaAliases = new List<string>();
			List<string> formulaTemplates = new List<string>();
			List<bool> formulasLazy = new List<bool>();
			List<IType> types = new List<IType>();
			List<string> names = new List<string>();
			List<string> classes = new List<string>();
			List<string[]> templates2 = new List<string[]>();
			List<string[]> propColumns = new List<string[]>();
			List<FetchMode> joinedFetchesList = new List<FetchMode>();
			List<CascadeStyle> cascades = new List<CascadeStyle>();
			List<bool> definedBySubclass = new List<bool>();
			List<int[]> propColumnNumbers = new List<int[]>();
			List<int[]> propFormulaNumbers = new List<int[]>();
			List<bool> columnSelectables = new List<bool>();
			List<bool> propNullables = new List<bool>();

			foreach (Property prop in persistentClass.SubclassPropertyClosureIterator)
			{
				names.Add(prop.Name);
				classes.Add(prop.PersistentClass.EntityName);
				bool isDefinedBySubclass = !thisClassProperties.Contains(prop);
				definedBySubclass.Add(isDefinedBySubclass);
				propNullables.Add(prop.IsOptional || isDefinedBySubclass); //TODO: is this completely correct?
				types.Add(prop.Type);

				string[] cols = new string[prop.ColumnSpan];
				string[] forms = new string[prop.ColumnSpan];
				int[] colnos = new int[prop.ColumnSpan];
				int[] formnos = new int[prop.ColumnSpan];
				int l = 0;
				bool lazy = prop.IsLazy && lazyAvailable;
				foreach (ISelectable thing in prop.ColumnIterator)
				{
					if (thing.IsFormula)
					{
						string template = thing.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
						formnos[l] = formulaTemplates.Count;
						colnos[l] = -1;
						formulaTemplates.Add(template);
						forms[l] = template;
						formulas.Add(thing.GetText(factory.Dialect));
						formulaAliases.Add(thing.GetAlias(factory.Dialect));
						formulasLazy.Add(lazy);
					}
					else
					{
						string colName = thing.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
						colnos[l] = columns.Count; //before add :-)
						formnos[l] = -1;
						columns.Add(colName);
						cols[l] = colName;
						aliases.Add(thing.GetAlias(factory.Dialect, prop.Value.Table));
						columnsLazy.Add(lazy);
						columnSelectables.Add(prop.IsSelectable);
					}
					l++;
				}
				propColumns.Add(cols);
				templates2.Add(forms);
				propColumnNumbers.Add(colnos);
				propFormulaNumbers.Add(formnos);

				joinedFetchesList.Add(prop.Value.FetchMode);
				cascades.Add(prop.CascadeStyle);
			}
			subclassColumnClosure = columns.ToArray();
			subclassColumnAliasClosure = aliases.ToArray();
			subclassColumnLazyClosure = columnsLazy.ToArray();
			subclassColumnSelectableClosure = columnSelectables.ToArray();

			subclassFormulaClosure = formulas.ToArray();
			subclassFormulaTemplateClosure = formulaTemplates.ToArray();
			subclassFormulaAliasClosure = formulaAliases.ToArray();
			subclassFormulaLazyClosure = formulasLazy.ToArray();

			subclassPropertyNameClosure = names.ToArray();
			subclassPropertySubclassNameClosure = classes.ToArray();
			subclassPropertyTypeClosure = types.ToArray();
			subclassPropertyNullabilityClosure = propNullables.ToArray();
			subclassPropertyFormulaTemplateClosure = templates2.ToArray();
			subclassPropertyColumnNameClosure = propColumns.ToArray();
			subclassPropertyColumnNumberClosure = propColumnNumbers.ToArray();
			subclassPropertyFormulaNumberClosure = propFormulaNumbers.ToArray();

			subclassPropertyCascadeStyleClosure = cascades.ToArray();
			subclassPropertyFetchModeClosure = joinedFetchesList.ToArray();

			propertyDefinedOnSubclass = definedBySubclass.ToArray();

			#endregion

			// Handle any filters applied to the class level
			filterHelper = new FilterHelper(persistentClass.FilterMap, factory.Dialect, factory.SQLFunctionRegistry);

			temporaryIdTableName = persistentClass.TemporaryIdTableName;
			temporaryIdTableDDL = persistentClass.TemporaryIdTableDDL;
		}
示例#30
0
		/// <summary>
		/// Return the names of all persistent (mapped) classes that extend or implement the
		/// given class or interface, accounting for implicit/explicit polymorphism settings
		/// and excluding mapped subclasses/joined-subclasses of other classes in the result.
		/// </summary>
		public string[] GetImplementors(string entityOrClassName)
		{
			string[] knownMap;
			if(entityNameImplementorsMap.TryGetValue(entityOrClassName,out knownMap))
			{
				return knownMap;
			}
			System.Type clazz = null;

			// NH Different implementation for performance: a class without at least a namespace sure can't be found by reflection
			if (entityOrClassName.IndexOf('.') > 0)
			{
				IEntityPersister checkPersister;
				// NH Different implementation: we have better performance checking, first of all, if we know the class
				// and take the System.Type directly from the persister (className have high probability to be entityName at least using Criteria or Linq)
				if (entityPersisters.TryGetValue(entityOrClassName, out checkPersister))
				{
					if(!checkPersister.EntityMetamodel.HasPocoRepresentation)
					{
						// we found the persister but it is a dynamic entity without class
						knownMap = new[] { entityOrClassName };
						entityNameImplementorsMap[entityOrClassName] = knownMap;
						return knownMap;
					}
					// NH : take care with this because we are forcing the Poco EntityMode
					clazz = checkPersister.GetMappedClass(EntityMode.Poco);
				}

				if (clazz == null)
				{
					try
					{
						clazz = ReflectHelper.ClassForFullNameOrNull(entityOrClassName);
					}
					catch (Exception)
					{
						clazz = null;
					}
				}
			}

			if (clazz == null)
			{
				// try to get the class from imported names
				string importedName = GetImportedClassName(entityOrClassName);
				if (importedName != null)
				{
					clazz = System.Type.GetType(importedName, false);
				}
			}

			if (clazz == null)
			{
				knownMap = new[] { entityOrClassName };
				entityNameImplementorsMap[entityOrClassName] = knownMap;
				return knownMap; //for a dynamic-class
			}

			var results = new List<string>();
			foreach (var q in entityPersisters.Values.OfType<IQueryable>())
			{
				string registeredEntityName = q.EntityName;
				// NH: as entity-name we are using the FullName but in HQL we allow just the Name, the class is mapped even when its FullName match the entity-name
				bool isMappedClass = entityOrClassName.Equals(registeredEntityName) || clazz.FullName.Equals(registeredEntityName);
				if (q.IsExplicitPolymorphism)
				{
					if (isMappedClass)
					{
						knownMap = new[] { registeredEntityName };
						entityNameImplementorsMap[entityOrClassName] = knownMap;
						return knownMap; // NOTE EARLY EXIT
					}
				}
				else
				{
					if (isMappedClass)
					{
						results.Add(registeredEntityName);
					}
					else
					{
						if (IsMatchingImplementor(entityOrClassName, clazz, q))
						{
							bool assignableSuperclass;
							if (q.IsInherited)
							{
								System.Type mappedSuperclass = GetEntityPersister(q.MappedSuperclass).GetMappedClass(EntityMode.Poco);
								assignableSuperclass = clazz.IsAssignableFrom(mappedSuperclass);
							}
							else
							{
								assignableSuperclass = false;
							}
							if (!assignableSuperclass)
							{
								results.Add(registeredEntityName);
							}
						}
					}
				}
			}
			knownMap = results.ToArray();
			entityNameImplementorsMap[entityOrClassName] = knownMap;
			return knownMap;
		}