public static IType GetPropertyType(
			ISessionFactory sessionFactory,
			Type classType,
			string propertyName)
		{
			string[] properties = propertyName.Split(new char[] { '.' });
			IClassMetadata currentMetadata = sessionFactory.GetClassMetadata(classType);
			IType currentType = null;
			foreach (string s in properties)
			{
				// get metadata from type, if necessary
				if (currentMetadata == null)
				{
					currentMetadata = sessionFactory.GetClassMetadata(currentType.ReturnedClass);
				}
				// get type from metadata
				if ("id".Equals(s))
				{
					currentType = currentMetadata.IdentifierType;
				}
				else
				{
					currentType = currentMetadata.GetPropertyType(s);
				}

				currentMetadata = null;
			}
			return currentType;
		}
		public static bool IsDynamicComponentDictionaryGetter(MethodInfo method, Expression targetObject, IEnumerable<Expression> arguments, ISessionFactory sessionFactory, out string memberName)
		{
			memberName = null;

			// A dynamic component must be an IDictionary with a string key.

			if (method.Name != "get_Item" || !typeof(IDictionary).IsAssignableFrom(targetObject.Type))
				return false;

			var key = arguments.First() as ConstantExpression;
			if (key == null || key.Type != typeof(string))
				return false;

			// The potential member name
			memberName = (string)key.Value;

			// Need the owning member (the dictionary).
			var member = targetObject as MemberExpression;
			if (member == null)
				return false;

			var memberPath = member.Member.Name;
			var metaData = sessionFactory.GetClassMetadata(member.Expression.Type);

			//Walk backwards if the owning member is not a mapped class (i.e a possible Component)
			targetObject = member.Expression;
			while (metaData == null && targetObject != null &&
			       (targetObject.NodeType == ExpressionType.MemberAccess || targetObject.NodeType == ExpressionType.Parameter ||
			        targetObject.NodeType == QuerySourceReferenceExpression.ExpressionType))
			{
				System.Type memberType;
				if (targetObject.NodeType == QuerySourceReferenceExpression.ExpressionType)
				{
					var querySourceExpression = (QuerySourceReferenceExpression) targetObject;
					memberType = querySourceExpression.Type;
				}
				else if (targetObject.NodeType == ExpressionType.Parameter)
				{
					var parameterExpression = (ParameterExpression) targetObject;
					memberType = parameterExpression.Type;
				}
				else //targetObject.NodeType == ExpressionType.MemberAccess
				{
					var memberExpression = ((MemberExpression) targetObject);
					memberPath = memberExpression.Member.Name + "." + memberPath;
					memberType = memberExpression.Type;
					targetObject = memberExpression.Expression;
				}
				metaData = sessionFactory.GetClassMetadata(memberType);
			}

			if (metaData == null)
				return false;

			// IDictionary can be mapped as collection or component - is it mapped as a component?
			var propertyType = metaData.GetPropertyType(memberPath);
			return (propertyType != null && propertyType.IsComponentType);
		}
Exemple #3
0
        public Model(ISessionFactory sessionfactory, Type type)
        {
            if (sessionfactory == null) throw new ArgumentNullException("sessionfactory");
            if (type == null) throw new ArgumentNullException("type");

            IsComponent = false;
            Type = type;
            Metadata = sessionfactory.GetClassMetadata(Type);
            Properties = new Dictionary<string, IType>();
            Components = new Dictionary<string, Model>();
            BelongsTos = new Dictionary<string, ManyToOneType>();
            OneToOnes = new Dictionary<string, OneToOneType>();
            Anys = new Dictionary<string, AnyType>();
            HasManys = new Dictionary<string, Collection>();
            HasAndBelongsToManys = new Dictionary<string, Collection>();

            PrimaryKey = new KeyValuePair<string, IType>(Metadata.IdentifierPropertyName, Metadata.IdentifierType);
            foreach (var name in Metadata.PropertyNames) {
                var prop = Metadata.GetPropertyType(name);
                CategorizeProperty(sessionfactory, prop, name);
            }
            Properties = new ReadOnlyDictionary<string, IType>(Properties);
            Components = new ReadOnlyDictionary<string, Model>(Components);
            BelongsTos = new ReadOnlyDictionary<string, ManyToOneType>(BelongsTos);
            OneToOnes = new ReadOnlyDictionary<string, OneToOneType>(OneToOnes);
            Anys = new ReadOnlyDictionary<string, AnyType>(Anys);
            HasManys = new ReadOnlyDictionary<string, Collection>(HasManys);
            HasAndBelongsToManys = new ReadOnlyDictionary<string, Collection>(HasAndBelongsToManys);
        }
		public static bool IsDynamicComponentDictionaryGetter(MethodInfo method, Expression targetObject, IEnumerable<Expression> arguments, ISessionFactory sessionFactory, out string memberName)
		{
			memberName = null;

			// A dynamic component must be an IDictionary with a string key.

			if (method.Name != "get_Item" || !typeof(IDictionary).IsAssignableFrom(targetObject.Type))
				return false;

			var key = arguments.First() as ConstantExpression;
			if (key == null || key.Type != typeof(string))
				return false;

			// The potential member name
			memberName = (string)key.Value;

			// Need the owning member (the dictionary).
			var member = targetObject as MemberExpression;
			if (member == null)
				return false;

			var metaData = sessionFactory.GetClassMetadata(member.Expression.Type);
			if (metaData == null)
				return false;

			// IDictionary can be mapped as collection or component - is it mapped as a component?
			var propertyType = metaData.GetPropertyType(member.Member.Name);
			return (propertyType != null && propertyType.IsComponentType);
		}
        private static Expression GetIdentifier(ISessionFactory sessionFactory, Expression expression)
        {
            if (expression.Type.IsPrimitive || expression.Type == typeof(string))
            {
                return(expression);
            }

            var classMetadata = sessionFactory.GetClassMetadata(expression.Type);

            if (classMetadata == null)
            {
                return(Expression.Constant(null));
            }

            var propertyName = classMetadata.IdentifierPropertyName;

            NHibernate.Type.EmbeddedComponentType componentType;
            if (propertyName == null && (componentType = classMetadata.IdentifierType as NHibernate.Type.EmbeddedComponentType) != null)
            {
                //The identifier is an embedded composite key. We only need one property from it for a null check
                propertyName = componentType.PropertyNames.First();
            }

            return(ConvertToObject(Expression.PropertyOrField(expression, propertyName)));
        }
Exemple #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ManagerCacheBaseT{TClass,TKey}"/> class.
 /// </summary>
 /// <param name="repository">
 /// The repository.
 /// </param>
 public ManagerCacheBaseT(IManagerBase <TClass, TKey> repository)
 {
     Repository     = repository;
     SessionFactory = ObjectFactory.GetInstance <ISessionFactory>();
     TimeSpan       = new TimeSpan(0, 0, 30, 0);
     classMetadata  = SessionFactory.GetClassMetadata(typeof(TClass));
     TimeQueryDb    = new DateTime(1900, 1, 1);
 }
        public IList <string> GetColumnNames <TEntity>()
        {
            global::NHibernate.Metadata.IClassMetadata classMedaData = _sessionFactory.GetClassMetadata(typeof(TEntity));
            IList <string> columnNames = new List <string>(classMedaData.PropertyNames);

            columnNames.Add(classMedaData.IdentifierPropertyName);
            return(columnNames);
        }
 /// <summary>
 /// Initializes the session that will be used to enumerate
 /// </summary>
 private void InitSession()
 {
     _session           = _sessionFactory.OpenSession();
     _session.FlushMode = FlushMode.Never;
     _tx = _session.BeginTransaction();
     try
     {
         //Handle the case of entity type (InitialLoad)
         if (_entityType != null)
         {
             _criteria = _session.CreateCriteria(_entityType);
             _criteria.SetCacheable(false);
             //If perform by id, add order to the criteria
             if (_performOrderById)
             {
                 IClassMetadata metadata   = _sessionFactory.GetClassMetadata(_entityType);
                 string         idPropName = metadata.IdentifierPropertyName;
                 if (idPropName != null)
                 {
                     _criteria.AddOrder(Order.Asc(idPropName));
                 }
             }
         }
         //Handle the case of Persistency.Query (GetEnumerator)
         else if (_persistencyQuery != null)
         {
             string select = _persistencyQuery.SqlQuery;
             _query = _session.CreateQuery(select);
             object[] preparedValues = _persistencyQuery.Parameters;
             if (preparedValues != null)
             {
                 for (int i = 0; i < preparedValues.Length; i++)
                 {
                     _query.SetParameter(i, preparedValues[i]);
                 }
             }
             _query.SetCacheable(false);
             _query.SetFlushMode(FlushMode.Never);
         }
         else
         {
             throw new Exception("NHibernateDataEnumerator must receive an Entity Type or a Query");
         }
     }
     catch (Exception ex)
     {
         if (_tx != null && _tx.IsActive)
         {
             _tx.Rollback();
         }
         if (_session.IsOpen)
         {
             _session.Close();
         }
         throw new Exception("Error while constructing an enumerator", ex);
     }
 }
        public static bool IsMapped <T>(ISessionFactory sessionFactory, string propertyName)
        {
            Type           type = typeof(T);
            IClassMetadata meta = sessionFactory.GetClassMetadata(type);

            var propertyNames = new List <string>(meta.PropertyNames);

            return(propertyNames.Contains(propertyName));
        }
Exemple #10
0
		public override object Instantiate(string clazz, EntityMode entityMode, object id)
		{
			logger.Debug("Instantiate: " + clazz + " " + entityMode + " " + id);
		    object instance = interceptor.Create(clazz, id);
		    if (instance != null)
		    {
		        sessionFactory.GetClassMetadata(clazz).SetIdentifier(instance, id, entityMode);
		    }
		    return instance;
		}
Exemple #11
0
        /// <summary>
        /// Add the Fetch clauses to the query according to the given expand paths, using the ICriteria API
        /// </summary>
        /// <param name="criteria">The query to expand</param>
        /// <param name="expandPaths">The names of the properties to expand.  May include nested paths of the form "Property/SubProperty"</param>
        /// <param name="sessionFactory">Provides the NHibernate metadata for the classes</param>
        /// <param name="expandMap">If provided, will be populated with the names of the expanded properties for each type.</param>
        /// <returns></returns>
        public static ICriteria ApplyExpansions(ICriteria criteria, string[] expandPaths, ISessionFactory sessionFactory, IDictionary <Type, List <string> > expandMap = null)
        {
            if (criteria == null)
            {
                throw new ArgumentException("Criteria cannot be null");
            }

            if (!expandPaths.Any())
            {
                throw new ArgumentException("Expansion Paths cannot be null");
            }

            foreach (var expand in expandPaths)
            {
                // We always start with the resulting element type
                var currentType = criteria.GetRootEntityTypeIfAvailable();
                var dotpath     = expand.Replace('/', '.');
                criteria = criteria.Fetch(SelectMode.JoinOnly, dotpath);

                // Add the types and properties to the expandMap so they will be serialized
                foreach (var seg in expand.Split('/'))
                {
                    if (expandMap != null && !expandMap.ContainsKey(currentType))
                    {
                        expandMap.Add(currentType, new List <string>());
                    }

                    var metadata = sessionFactory.GetClassMetadata(currentType);
                    if (metadata == null)
                    {
                        throw new ArgumentException("Type '" + currentType + "' not recognized as a valid type for this Context");
                    }

                    // Gather information about the property
                    var propInfo = currentType.GetProperty(seg);

                    if (propInfo == null)
                    {
                        throw new ArgumentException("Type '" + currentType.Name + "' does not have property '" + seg + "'");
                    }

                    if (expandMap != null)
                    {
                        expandMap[currentType].Add(seg);
                    }

                    var propType = propInfo.PropertyType;

                    currentType = propType;
                }
            }

            return(criteria);
        }
        private static Expression GetIdentifier(ISessionFactory sessionFactory, Expression expression)
        {
            var classMetadata = sessionFactory.GetClassMetadata(expression.Type);

            if (classMetadata == null)
            {
                return(Expression.Constant(null));
            }

            return(ConvertToObject(Expression.PropertyOrField(expression, classMetadata.IdentifierPropertyName)));
        }
        public async Task Handle(BaseDomainEvent notification, CancellationToken cancellationToken)
        {
            if (sessionFactory.GetClassMetadata(notification.GetType()) == null)
            {
                return;
            }

            using var statelessSession = sessionFactory.OpenStatelessSession();
            using var transaction      = statelessSession.BeginTransaction(IsolationLevel.ReadCommitted);

            await statelessSession.InsertAsync(notification, cancellationToken);

            await transaction.CommitAsync(cancellationToken);
        }
 public override object Instantiate(string clazz, EntityMode entityMode, object id)
 {
     if (entityMode == EntityMode.Poco)
     {
         Type type = Type.GetType(clazz);
         if (type != null)
         {
             var instance = DataBindingFactory.Create(type);
             _sessionFactory.GetClassMetadata(clazz).SetIdentifier(instance, id, entityMode);
             return(instance);
         }
     }
     return(base.Instantiate(clazz, entityMode, id));
 }
        public void WillUseRegisteredAssembliesToLookForRawMappingXmlEvenIfThereAreNoActiveRecordTypesInThatAssembly()
        {
            ActiveRecordStarter.ResetInitializationFlag();
            ActiveRecordStarter.Initialize(
                typeof(RegisterNHibernateClassMapping).Assembly,
                GetConfigSource()
                );
            ISessionFactory factory = ActiveRecordMediator.GetSessionFactoryHolder()
                                      .GetSessionFactory(typeof(ActiveRecordBase));
            IClassMetadata metadata = factory
                                      .GetClassMetadata(typeof(NHibernateClass));

            Assert.IsNotNull(metadata);
        }
        public ISession Get(Type modelType)
        {
            if (_fooSessionFactory.GetClassMetadata(modelType) != null)
            {
                return(_serviceProvider.GetService <FooSession>().Session);
            }

            if (_barSessionFactory.GetClassMetadata(modelType) != null)
            {
                return(_serviceProvider.GetService <BarSession>().Session);
            }

            return(null);
        }
Exemple #17
0
        public Repository(ISessionFactory sessionFactory, ISession session)
        {
            this.session        = session ?? throw new ArgumentNullException("session", "未能获取 ISession的实例。");
            this.sessionFactory = sessionFactory ?? throw new ArgumentNullException("sessionFactory", "仓储层需要根据 ISessionFactory 获取Session,但未能获取 ISessionFactory 的实例。");

            ClassMetadata          = sessionFactory.GetClassMetadata(persistentClass);
            identifierPropertyName = ClassMetadata.IdentifierPropertyName;
            entityName             = ClassMetadata.EntityName;
            queryAllString         = $"from {entityName}";
            allQuery = new DetachedQuery($"from {entityName}");

            allCountQuery     = new DetachedQuery($"select count(*) from {entityName}");
            inIdentitiesQuery = new DetachedQuery($"from {entityName} where {identifierPropertyName} in (:identities)");
        }
Exemple #18
0
        /// <summary>
        /// 지정된 엔티티 형식이 <paramref name="sessionFactory"/>에 매핑된 엔티티인지 파악합니다.
        /// </summary>
        /// <param name="sessionFactory">엔티티가 매핑되었을 SessionFactory</param>
        /// <param name="entityType">엔티티의 형식</param>
        /// <returns>SessionFactory에 엔티티 형식이 매핑되었으면 True, 아니면 False</returns>
        /// <seealso cref="NHibernateProxyHelper.GetClassWithoutInitializingProxy"/>
        public static bool IsMappedEntity(this ISessionFactory sessionFactory, Type entityType)
        {
            if (entityType == null)
            {
                return(false);
            }

            if (IsDebugEnabled)
            {
                log.Debug("Current SessionFactory[{0}]에 엔티티 형식[{1}]가 매핑되었는지 확인합니다...",
                          sessionFactory.GetSessionFactoryName(), entityType.FullName);
            }

            return(sessionFactory.GetClassMetadata(entityType.GetUnproxiedType()) != null);
        }
Exemple #19
0
            public static void CleanUpTable <T>(ISessionFactory sessionFactory)
            {
                var metadata = sessionFactory.GetClassMetadata(typeof(T)) as NHibernate.Persister.Entity.AbstractEntityPersister;
                var table    = metadata.TableName;

                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        var deleteAll = string.Format("DELETE FROM {0}".StringFormat(table));
                        session.CreateSQLQuery(deleteAll).ExecuteUpdate();
                        transaction.Commit();
                    }
                }
            }
Exemple #20
0
        /// <summary>
        /// Force initialzation of a possibly proxied object tree up to the maxDepth.
        ///   Once the maxDepth is reached, entity properties will be replaced with
        ///   placeholder objects having only the identifier property populated.
        /// </summary>
        /// <typeparam name="T">
        /// Тип
        /// </typeparam>
        /// <param name="persistentObject">
        /// The persistent Object.
        /// </param>
        /// <param name="sessionFactory">
        /// The session Factory.
        /// </param>
        /// <param name="maxDepth">
        /// The max Depth.
        /// </param>
        /// <returns>
        /// The <see cref="T"/>.
        /// </returns>
        public static T UnproxyObjectTree <T>(this T persistentObject, ISessionFactory sessionFactory, int maxDepth)
        {
            // Determine persistent type of the object
            var persistentType = persistentObject.GetUnproxiedType();

            var classMetadata = sessionFactory.GetClassMetadata(persistentType);

            // If we've already reached the max depth, we will return a placeholder object
            if (maxDepth < 0)
            {
                return(CreatePlaceholder(persistentObject, persistentType, classMetadata));
            }

            // Now lets go ahead and make sure everything is unproxied
            var unproxiedObject = persistentObject.Unproxy(sessionFactory);

            // Iterate through each property and unproxy entity types
            for (var i = 0; i < classMetadata.PropertyTypes.Length; i++)
            {
                var propertyType = classMetadata.PropertyTypes[i];
                var propertyName = classMetadata.PropertyNames[i];
                var propertyInfo = persistentType.GetProperty(propertyName);

                // Unproxy of collections is not currently supported.  We set the collection property to null.
                if (propertyType.IsCollectionType)
                {
                    propertyInfo.SetValue(unproxiedObject, null, null);
                    continue;
                }

                if (!propertyType.IsEntityType)
                {
                    continue;
                }

                object propertyValue = propertyInfo.GetValue(unproxiedObject, null);

                if (propertyValue == null)
                {
                    continue;
                }

                propertyInfo.SetValue(unproxiedObject, propertyValue.UnproxyObjectTree(sessionFactory, maxDepth - 1), null);
            }

            return(unproxiedObject);
        }
Exemple #21
0
        /// <summary>
        /// Gets the list of database column names for an entity
        /// </summary>
        /// <param name="sessionFactory">NHibernate SessionFactory</param>
        /// <param name="entity">A mapped entity</param>
        /// <returns>List of column names</returns>
        public static List <string> GetPropertyColumnNames(ISessionFactory sessionFactory, object entity)
        {
            Type type = entity.GetType();
            // This has some cool methods and properties so check it out
            var metaData = sessionFactory.GetClassMetadata(type.ToString());
            // This has some even cooler methods and properties so definitely check this out
            var           entityPersister = (AbstractEntityPersister)metaData;
            var           propertyNames   = entityPersister.PropertyNames;
            List <string> columnNames     = new List <string>();

            foreach (var propertyName in propertyNames)
            {
                var columnName = entityPersister.GetPropertyColumnNames(propertyName);
                columnNames.Add(columnName.Length != 0 ? columnName[0] : null);
            }
            return(columnNames);
        }
Exemple #22
0
        public Dictionary <string, int> GetStringFieldLengths()
        {
            Dictionary <string, int> temp = new Dictionary <string, int>();

            IClassMetadata metadata = _sessionFactory.GetClassMetadata(typeof(T));

            foreach (string propertyName in metadata.PropertyNames)
            {
                IType      propertyType = metadata.GetPropertyType(propertyName);
                StringType st           = propertyType as StringType;
                if (st != null && st.SqlType.Length > 0)
                {
                    temp.Add(propertyName, st.SqlType.Length);
                }
            }
            return(temp);
        }
Exemple #23
0
        public static ICriteria FetchAllProperties <TEntity>(this ICriteria criteria, ISessionFactory sessionFactory)
        {
            var entityType = typeof(TEntity);
            var metaData   = sessionFactory.GetClassMetadata(entityType);

            for (var i = 0; i < metaData.PropertyNames.Length; i++)
            {
                var propType = metaData.PropertyTypes[i];
                // get eagerly mapped associations to other entities
                if (propType.IsAssociationType && !metaData.PropertyLaziness[i])
                {
                    //criteria = criteria.SetFetchMode(propType.Name, FetchMode.Eager);
                    criteria = criteria.Fetch(SelectMode.JoinOnly, propType.Name);
                }
            }

            return(criteria);
        }
Exemple #24
0
        /// <summary>
        /// GetId
        /// </summary>
        /// <param name="sessionFactory"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static object GetId(ISessionFactory sessionFactory, object entity)
        {
            if (entity == null)
            {
                return(null);
            }
            Type entityType = entity.GetType();

            NHibernate.Metadata.IClassMetadata entityMeta = sessionFactory.GetClassMetadata(entityType);
            if (entityMeta != null)
            {
                return(entityMeta.GetIdentifier(entity, EntityMode.Map));
            }
            else
            {
                return(null);
            }
        }
Exemple #25
0
        /// <summary>
        /// Gets the property database information.
        /// </summary>
        /// <param name="entityType">
        /// Type of the entity.
        /// </param>
        /// <param name="propertyPath">
        /// The property path.
        /// </param>
        /// <returns>
        /// A <see cref="DbInfoDto"/>
        /// </returns>
        public DbInfoDto GetPropertyDatabaseInformation(Type entityType, string propertyPath)
        {
            Check.IsNotNull(entityType, "entityType is required.");
            Check.IsNotNullOrWhitespace(propertyPath, "propertyPath cannot be empty or whitespace.");

            var classMapping = _sessionFactory.GetClassMetadata(entityType);
            var persister    = classMapping as AbstractEntityPersister;
            var dbInfo       = new DbInfoDto();

            if (persister != null)
            {
                dbInfo.Table    = persister.TableName;
                dbInfo.Column   = string.Join(",", persister.GetPropertyColumnNames(propertyPath));
                dbInfo.DataType = persister.GetPropertyType(propertyPath).Name;
            }

            return(dbInfo);
        }
Exemple #26
0
        /// <summary>
        /// Returns the list of property and field names that should be serialized on a given type.
        /// </summary>
        /// <param name="objectType"></param>
        /// <returns></returns>
        protected override List <MemberInfo> GetSerializableMembers(Type objectType)
        {
            var meta    = sessionFactory.GetClassMetadata(objectType);
            var members = base.GetSerializableMembers(objectType);

            var properties = members.OfType <PropertyInfo>().ToList();

            properties.RemoveAll(p => !IsIncluded(meta, p.PropertyType, objectType, p.Name));

            var fields = members.OfType <FieldInfo>().ToList();

            fields.RemoveAll(f => !IsIncluded(meta, f.FieldType, objectType, f.Name));

            members.Clear();
            members.AddRange(properties);
            members.AddRange(fields);

            return(members);
        }
 static Expression GetIdentifier(ISessionFactory sessionFactory, IEnumerable <ExpressionHolder> expressions, ExpressionHolder e)
 {
     foreach (var holders in expressions)
     {
         if (holders.Tuple == e.Tuple)
         {
             var memberExpression = holders.Expression as MemberExpression;
             if (memberExpression != null)
             {
                 var expression    = memberExpression.Expression;
                 var classMetadata = sessionFactory.GetClassMetadata(expression.Type);
                 if (classMetadata != null)
                 {
                     return(ConvertToObject(Expression.PropertyOrField(expression, classMetadata.IdentifierPropertyName)));
                 }
             }
         }
     }
     return(Expression.Constant(null));
 }
Exemple #28
0
        public static bool IsDynamicComponentDictionaryGetter(MethodInfo method, Expression targetObject, ReadOnlyCollection <Expression> arguments, ISessionFactory sessionFactory, out string memberName)
        {
            memberName = null;

            // A dynamic component must be an IDictionary with a string key.

            if (method.Name != "get_Item" || !typeof(IDictionary).IsAssignableFrom(targetObject.Type))
            {
                return(false);
            }

            var key = arguments.First() as ConstantExpression;

            if (key == null || key.Type != typeof(string))
            {
                return(false);
            }

            // The potential member name
            memberName = (string)key.Value;

            // Need the owning member (the dictionary).
            var member = targetObject as MemberExpression;

            if (member == null)
            {
                return(false);
            }

            var metaData = sessionFactory.GetClassMetadata(member.Expression.Type);

            if (metaData == null)
            {
                return(false);
            }

            // IDictionary can be mapped as collection or component - is it mapped as a component?
            var propertyType = metaData.GetPropertyType(member.Member.Name);

            return(propertyType != null && propertyType.IsComponentType);
        }
Exemple #29
0
        public Model(ISessionFactory sessionfactory, ComponentType type)
        {
            if (type == null) throw new ArgumentNullException("type");

            IsComponent = true;
            Type = type.ReturnedClass;
            ComponentType = type;
            Metadata = sessionfactory.GetClassMetadata(Type);
            Properties = new Dictionary<string, IType>();
            Components = new Dictionary<string, Model>();
            BelongsTos = new Dictionary<string, ManyToOneType>();
            OneToOnes = new Dictionary<string, OneToOneType>();
            Anys = new Dictionary<string, AnyType>();
            HasManys = new Dictionary<string, Collection>();
            HasAndBelongsToManys = new Dictionary<string, Collection>();
            foreach (var pc in type.PropertyNames) {
                var index = type.GetPropertyIndex(pc);
                var x = type.Subtypes[index];
                CategorizeProperty(sessionfactory, x, pc);
            }
        }
Exemple #30
0
        /// <summary>
        /// Force initialization of a proxy or persistent collection.
        /// </summary>
        /// <typeparam name="T">
        /// Тип
        /// </typeparam>
        /// <param name="persistentObject">
        /// a persistable object, proxy, persistent collection or null
        /// </param>
        /// <param name="sessionFactory">
        /// The session Factory.
        /// </param>
        /// <exception cref="HibernateException">
        /// if we can't initialize the proxy at this time, eg. the Session was closed
        /// </exception>
        /// <returns>
        /// The <see cref="T"/>.
        /// </returns>
        public static T Unproxy <T>(this T persistentObject, ISessionFactory sessionFactory)
        {
            var proxy = persistentObject as INHibernateProxy;

            if (proxy != null)
            {
                try
                {
                    return((T)proxy.HibernateLazyInitializer.GetImplementation());
                }
                catch (LazyInitializationException)
                {
                    var persistentType = persistentObject.GetUnproxiedType();

                    var classMetadata = sessionFactory.GetClassMetadata(persistentType);

                    return(CreatePlaceholder(persistentObject, persistentType, classMetadata));
                }
            }

            return(persistentObject);
        }
Exemple #31
0
        public Model(ISessionFactory sessionfactory, Type type)
        {
            if (sessionfactory == null)
            {
                throw new ArgumentNullException("sessionfactory");
            }
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            IsComponent          = false;
            Type                 = type;
            Metadata             = sessionfactory.GetClassMetadata(Type);
            Properties           = new Dictionary <string, IType>();
            Components           = new Dictionary <string, Model>();
            BelongsTos           = new Dictionary <string, ManyToOneType>();
            OneToOnes            = new Dictionary <string, OneToOneType>();
            Anys                 = new Dictionary <string, AnyType>();
            HasManys             = new Dictionary <string, Collection>();
            HasAndBelongsToManys = new Dictionary <string, Collection>();

            PrimaryKey = new KeyValuePair <string, IType>(Metadata.IdentifierPropertyName, Metadata.IdentifierType);
            foreach (var name in Metadata.PropertyNames)
            {
                var prop = Metadata.GetPropertyType(name);
                CategorizeProperty(sessionfactory, prop, name);
            }
            Properties           = new ReadOnlyDictionary <string, IType>(Properties);
            Components           = new ReadOnlyDictionary <string, Model>(Components);
            BelongsTos           = new ReadOnlyDictionary <string, ManyToOneType>(BelongsTos);
            OneToOnes            = new ReadOnlyDictionary <string, OneToOneType>(OneToOnes);
            Anys                 = new ReadOnlyDictionary <string, AnyType>(Anys);
            HasManys             = new ReadOnlyDictionary <string, Collection>(HasManys);
            HasAndBelongsToManys = new ReadOnlyDictionary <string, Collection>(HasAndBelongsToManys);
        }
        /// <summary> Gets property mapping to data source columns
        /// </summary>
        /// <returns></returns>
        public StringDictionary GetPropertyToColumnMapping()
        {
            if (null != _propertyToColumnMapping)
            {
                return(_propertyToColumnMapping);
            }

            _propertyToColumnMapping = new StringDictionary();
            return(ExecInSessionRO <StringDictionary>(session =>
            {
                ISessionFactory sessionFactory = session.SessionFactory;
                var metaData = sessionFactory.GetClassMetadata(typeof(TImpl));
                var entityPersister = (AbstractEntityPersister)metaData;
                if (entityPersister.HasIdentifierProperty)
                {
                    string idPropertyName = entityPersister.IdentifierPropertyName;
                    _propertyToColumnMapping.Add(idPropertyName
                                                 , (string.IsNullOrEmpty(entityPersister.IdentifierColumnNames[0]) ? idPropertyName : entityPersister.IdentifierColumnNames[0]));
                }
                var propertyNames = entityPersister.PropertyNames;
                foreach (var propertyName in propertyNames)
                {
                    var columnNameArray = entityPersister.GetPropertyColumnNames(propertyName);
                    if (columnNameArray.Count() > 0)
                    {
                        _propertyToColumnMapping.Add(propertyName, (string.IsNullOrEmpty(columnNameArray[0]) ? propertyName : columnNameArray[0]));
                    }
                    else
                    {
                        _propertyToColumnMapping.Add(propertyName, propertyName);
                    }
                }
                return _propertyToColumnMapping;
            }
                                                      ));
        }
Exemple #33
0
        /// <summary>
        /// Add the Fetch clauses to the query according to the given expand paths
        /// </summary>
        /// <param name="queryable">The query to expand</param>
        /// <param name="expandPaths">The names of the properties to expand.  May include nested paths of the form "Property/SubProperty"</param>
        /// <param name="sessionFactory">Provides the NHibernate metadata for the classes</param>
        /// <param name="expandMap">Will be populated with the names of the expanded properties for each type.</param>
        /// <param name="expandCollections">If true, eagerly fetch collections. Caution: this causes problems with $skip and $top operations.
        ///     Default is false.  expandMap will still be populated with the collection property, so it will be lazy loaded.
        ///     Be sure to set default_batch_fetch_size in the configuration for lazy loaded collections.</param>
        /// <returns></returns>
        public IQueryable ApplyExpansions(IQueryable queryable, string[] expandPaths, ExpandTypeMap expandMap, bool expandCollections = false)
        {
            if (queryable == null)
            {
                throw new ArgumentException("Query cannot be null");
            }

            var nHibQuery = queryable.Provider as DefaultQueryProvider;

            if (nHibQuery == null)
            {
                throw new ArgumentException("Expansion only supported on INHibernateQueryable queries");
            }

            if (!expandPaths.Any())
            {
                throw new ArgumentException("Expansion Paths cannot be null");
            }

            var currentQueryable = queryable;

            foreach (string expand in expandPaths)
            {
                // We always start with the resulting element type
                var currentType  = currentQueryable.ElementType;
                var isFirstFetch = true;
                var isInvoking   = true;

                // split on '/' or '.'
                var segments = expand.Split('/', '.');
                expandMap.Deepen(segments.Length);
                foreach (string seg in segments)
                {
                    if (expandMap != null && !expandMap.map.ContainsKey(currentType))
                    {
                        expandMap.map.Add(currentType, new List <string>());
                    }

                    IClassMetadata metadata = sessionFactory.GetClassMetadata(currentType);
                    if (metadata == null)
                    {
                        throw new ArgumentException("Type '" + currentType + "' not recognized as a valid type for this Context");
                    }

                    // Gather information about the property
                    var propInfo = currentType.GetProperty(seg);

                    if (propInfo == null)
                    {
                        throw new ArgumentException("Type '" + currentType.Name + "' does not have property '" + seg + "'");
                    }
                    if (expandMap != null && !expandMap.map[currentType].Contains(seg))
                    {
                        expandMap.map[currentType].Add(seg);
                    }

                    var propType     = propInfo.PropertyType;
                    var metaPropType = metadata.GetPropertyType(seg);

                    // When this is the first segment of a path, we have to use Fetch instead of ThenFetch
                    var propFetchFunctionName = (isFirstFetch ? "Fetch" : "ThenFetch");

                    // The delegateType is a type for the lambda creation to create the correct return value
                    System.Type delegateType;

                    if (metaPropType.IsCollectionType)
                    {
                        // We have to use "FetchMany" or "ThenFetchMany" when the target property is a collection
                        propFetchFunctionName += "Many";

                        // We only support IList<T> or something similar
                        propType     = propType.GetGenericArguments().Single();
                        delegateType = typeof(Func <,>).MakeGenericType(currentType,
                                                                        typeof(IEnumerable <>).MakeGenericType(propType));
                        if (!expandCollections)
                        {
                            // if we don't expand this collection, we won't invoke any sub-expansions of it either
                            // but we still need to traverse the tree top populate expandMap
                            isInvoking = false;
                        }
                    }
                    else
                    {
                        delegateType = typeof(Func <,>).MakeGenericType(currentType, propType);
                    }

                    if (isInvoking)
                    {
                        // Get the correct extension method (Fetch, FetchMany, ThenFetch, or ThenFetchMany)
                        var fetchMethodInfo = typeof(EagerFetchingExtensionMethods).GetMethod(propFetchFunctionName,
                                                                                              BindingFlags.Static |
                                                                                              BindingFlags.Public |
                                                                                              BindingFlags.InvokeMethod);
                        var fetchMethodTypes = new List <System.Type>();
                        fetchMethodTypes.AddRange(currentQueryable.GetType().GetGenericArguments().Take(isFirstFetch ? 1 : 2));
                        fetchMethodTypes.Add(propType);
                        fetchMethodInfo = fetchMethodInfo.MakeGenericMethod(fetchMethodTypes.ToArray());

                        // Create an expression of type new delegateType(x => x.{seg.Name})
                        var exprParam  = System.Linq.Expressions.Expression.Parameter(currentType, "x");
                        var exprProp   = System.Linq.Expressions.Expression.Property(exprParam, seg);
                        var exprLambda = System.Linq.Expressions.Expression.Lambda(delegateType, exprProp,
                                                                                   new System.Linq.Expressions.
                                                                                   ParameterExpression[] { exprParam });

                        // Call the *Fetch* function
                        var args = new object[] { currentQueryable, exprLambda };
                        currentQueryable = (IQueryable)fetchMethodInfo.Invoke(null, args) as IQueryable;
                    }
                    currentType  = propType;
                    isFirstFetch = false;
                }
            }

            return(currentQueryable);
        }
Exemple #34
0
 public static NHibernate.Persister.Entity.AbstractEntityPersister getMetaData <T>()
 {
     return(sessionFactory.GetClassMetadata(typeof(T))
            as NHibernate.Persister.Entity.AbstractEntityPersister);
 }
Exemple #35
0
        /// <summary>
        /// Add the Fetch clauses to the query according to the given expand paths, using the ICriteria API
        /// </summary>
        /// <param name="criteria">The query to expand</param>
        /// <param name="expandPaths">The names of the properties to expand.  May include nested paths of the form "Property/SubProperty"</param>
        /// <param name="sessionFactory">Provides the NHibernate metadata for the classes</param>
        /// <param name="expandMap">If provided, will be populated with the names of the expanded properties for each type.</param>
        /// <returns></returns>
        public static ICriteria ApplyExpansions(ICriteria criteria, string[] expandPaths, ISessionFactory sessionFactory, IDictionary<Type, List<string>> expandMap = null)
        {
            if (criteria == null) throw new ArgumentException("Criteria cannot be null");

            if (!expandPaths.Any()) throw new ArgumentException("Expansion Paths cannot be null");

            foreach (string expand in expandPaths)
            {
                // We always start with the resulting element type
                var currentType = criteria.GetRootEntityTypeIfAvailable();
                var dotpath = expand.Replace('/', '.');
                criteria.SetFetchMode(dotpath, FetchMode.Eager);

                // Add the types and properties to the expandMap so they will be serialized
                foreach (string seg in expand.Split('/'))
                {
                    if (expandMap != null && !expandMap.ContainsKey(currentType))
                        expandMap.Add(currentType, new List<string>());

                    IClassMetadata metadata = sessionFactory.GetClassMetadata(currentType);
                    if (metadata == null)
                    {
                        throw new ArgumentException("Type '" + currentType + "' not recognized as a valid type for this Context");
                    }

                    // Gather information about the property
                    var propInfo = currentType.GetProperty(seg);

                    if (propInfo == null)
                    {
                        throw new ArgumentException("Type '" + currentType.Name + "' does not have property '" + seg + "'");
                    }
                    if (expandMap != null) expandMap[currentType].Add(seg);
                    var propType = propInfo.PropertyType;

                    currentType = propType;
                }
            }

            return criteria;
        }
 public static string GetRootTableName(this ISessionFactory source, Type entityType)
 {
     return(((ILockable)source.GetClassMetadata(entityType)).RootTableName);
 }
        /// <summary>
        /// ���MasterDetail�µ�Detail Property Name
        /// </summary>
        /// <param name="sessionFactory"></param>
        /// <param name="masterType"></param>
        /// <param name="detailType"></param>
        /// <returns></returns>
        public static string GetOnetoManyPropertyName(ISessionFactory sessionFactory, Type masterType, Type detailType)
        {
            if (!s_collectionPropertyNames.ContainsKey(detailType))
            {
                s_collectionPropertyNames[detailType] = new Dictionary<Type, string>();
            }
            if (!s_collectionPropertyNames[detailType].ContainsKey(masterType))
            {
                NHibernate.Metadata.IClassMetadata metadata = sessionFactory.GetClassMetadata(detailType.FullName);

                for (int i = 0; i < metadata.PropertyTypes.Length; ++i)
                {
                    NHibernate.Type.ManyToOneType manyToOneType = metadata.PropertyTypes[i] as NHibernate.Type.ManyToOneType;
                    if (manyToOneType != null && manyToOneType.ReturnedClass == masterType)
                    {
                        s_collectionPropertyNames[detailType][masterType] = metadata.PropertyNames[i];
                        break;
                    }

                    NHibernate.Type.OneToOneType oneToOneType = metadata.PropertyTypes[i] as NHibernate.Type.OneToOneType;
                    if (oneToOneType != null && oneToOneType.ReturnedClass == masterType)
                    {
                        s_collectionPropertyNames[detailType][masterType] = metadata.PropertyNames[i];
                        break;
                    }
                }
            }

            return s_collectionPropertyNames[detailType][masterType];
        }
Exemple #38
0
        /// <summary>
        /// Add the Fetch clauses to the query according to the given expand paths
        /// </summary>
        /// <param name="queryable">The query to expand</param>
        /// <param name="expandPaths">The names of the properties to expand.  May include nested paths of the form "Property/SubProperty"</param>
        /// <param name="sessionFactory">Provides the NHibernate metadata for the classes</param>
        /// <param name="expandMap">If provided, will be populated with the names of the expanded properties for each type.</param>
        /// <returns></returns>
        public static IQueryable ApplyExpansions(IQueryable queryable, string[] expandPaths, ISessionFactory sessionFactory, IDictionary<Type, List<string>> expandMap = null)
        {
            if (queryable == null) throw new ArgumentException("Query cannot be null");

            var nHibQuery = queryable.Provider as DefaultQueryProvider;
            if (nHibQuery == null) throw new ArgumentException("Expansion only supported on INHibernateQueryable queries");

            if (!expandPaths.Any()) throw new ArgumentException("Expansion Paths cannot be null");

            var currentQueryable = queryable;
            foreach (string expand in expandPaths)
            {
                // We always start with the resulting element type
                var currentType = currentQueryable.ElementType;
                var isFirstFetch = true;
                foreach (string seg in expand.Split('/'))
                {
                    if (expandMap != null && !expandMap.ContainsKey(currentType))
                        expandMap.Add(currentType, new List<string>());

                    IClassMetadata metadata = sessionFactory.GetClassMetadata(currentType);
                    if (metadata == null)
                    {
                        throw new ArgumentException("Type '" + currentType + "' not recognized as a valid type for this Context");
                    }

                    // Gather information about the property
                    var propInfo = currentType.GetProperty(seg);

                    if (propInfo == null)
                    {
                        throw new ArgumentException("Type '" + currentType.Name + "' does not have property '" + seg + "'");
                    }
                    if (expandMap != null) expandMap[currentType].Add(seg);
                    var propType = propInfo.PropertyType;
                    var metaPropType = metadata.GetPropertyType(seg);

                    // When this is the first segment of a path, we have to use Fetch instead of ThenFetch
                    var propFetchFunctionName = (isFirstFetch ? "Fetch" : "ThenFetch");

                    // The delegateType is a type for the lambda creation to create the correct return value
                    System.Type delegateType;

                    if (metaPropType.IsCollectionType)
                    {
                        // We have to use "FetchMany" or "ThenFetchMany" when the target property is a collection
                        propFetchFunctionName += "Many";

                        // We only support IList<T> or something similar
                        propType = propType.GetGenericArguments().Single();
                        delegateType = typeof(Func<,>).MakeGenericType(currentType,
                                                                        typeof(IEnumerable<>).MakeGenericType(propType));
                    }
                    else
                    {
                        delegateType = typeof(Func<,>).MakeGenericType(currentType, propType);
                    }

                    // Get the correct extension method (Fetch, FetchMany, ThenFetch, or ThenFetchMany)
                    var fetchMethodInfo = typeof(EagerFetchingExtensionMethods).GetMethod(propFetchFunctionName,
                                                                                      BindingFlags.Static |
                                                                                      BindingFlags.Public |
                                                                                      BindingFlags.InvokeMethod);
                    var fetchMethodTypes = new List<System.Type>();
                    fetchMethodTypes.AddRange(currentQueryable.GetType().GetGenericArguments().Take(isFirstFetch ? 1 : 2));
                    fetchMethodTypes.Add(propType);
                    fetchMethodInfo = fetchMethodInfo.MakeGenericMethod(fetchMethodTypes.ToArray());

                    // Create an expression of type new delegateType(x => x.{seg.Name})
                    var exprParam = System.Linq.Expressions.Expression.Parameter(currentType, "x");
                    var exprProp = System.Linq.Expressions.Expression.Property(exprParam, seg);
                    var exprLambda = System.Linq.Expressions.Expression.Lambda(delegateType, exprProp,
                                                                               new System.Linq.Expressions.
                                                                                   ParameterExpression[] { exprParam });

                    // Call the *Fetch* function
                    var args = new object[] { currentQueryable, exprLambda };
                    currentQueryable = (IQueryable)fetchMethodInfo.Invoke(null, args) as IQueryable;

                    currentType = propType;
                    isFirstFetch = false;
                }
            }

            return currentQueryable;
        }
        /// <summary>
        /// ����Metadata�õ���������(Path�ԣ�����.�ָ�����Collection���򷵻�Collection���ڲ�Type��
        /// </summary>
        /// <param name="sessionFactory"></param>
        /// <param name="type"></param>
        /// <param name="fullPropertyName"></param>
        /// <param name="hasCollection"></param>
        /// <returns></returns>
        public static Type GetPropertyType(ISessionFactory sessionFactory, Type type, string fullPropertyName, out bool hasCollection)
        {
            hasCollection = false;
            if (string.IsNullOrEmpty(fullPropertyName))
                return null;
            string dictKey = type.ToString() + "#" + fullPropertyName;

            lock (s_propertyTypesHasCollection)
            {
                if (!s_propertyTypes.ContainsKey(dictKey))
                {
                    NHibernate.Metadata.IClassMetadata classMetadata = sessionFactory.GetClassMetadata(type);
                    if (classMetadata == null)
                    {
                        throw new NotSupportedException("There is no Metadata of type " + type.ToString());
                    }
                    NHibernate.Type.IType destType = null;
                    Type innerType = null;

                    NHibernate.Type.ComponentType componentType = null;
                    string[] ss = fullPropertyName.Split(new char[] { ':', '.' });
                    for (int i = 0; i < ss.Length; ++i)
                    {
                        TryRemoveJoinTypeChar(ref ss[i]);
                        if (componentType == null)
                        {
                            destType = classMetadata.GetPropertyType(ss[i]);
                        }
                        else
                        {
                            for (int j = 0; j < componentType.PropertyNames.Length; ++j)
                            {
                                if (componentType.PropertyNames[j] == ss[i])
                                {
                                    destType = componentType.Subtypes[j];
                                    break;
                                }
                            }
                        }
                        componentType = destType as NHibernate.Type.ComponentType;

                        if (componentType == null)
                        {
                            if (destType.IsCollectionType)
                            {
                                //System.Collections.Generic.IList`1[[Hd.Model.Jk2.��������ҵ����, Hd.Model.Jk2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
                                innerType = Feng.Utils.ReflectionHelper.GetGenericUnderlyingType(destType.ReturnedClass);
                                classMetadata = sessionFactory.GetClassMetadata(innerType);

                                hasCollection = true;
                            }
                            else
                            {
                                classMetadata = sessionFactory.GetClassMetadata(destType.ReturnedClass);
                            }
                        }
                    }

                    if (!destType.IsCollectionType)
                    {
                        s_propertyTypes[dictKey] = destType.ReturnedClass;
                    }
                    else
                    {
                        s_propertyTypes[dictKey] = innerType;
                    }

                    s_propertyTypesHasCollection[dictKey] = hasCollection;
                }

                hasCollection = s_propertyTypesHasCollection[dictKey];
                return s_propertyTypes[dictKey];
            }
        }
        /// <summary>
        /// GetId
        /// </summary>
        /// <param name="sessionFactory"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static object GetId(ISessionFactory sessionFactory, object entity)
        {
            if (entity == null)
            {
                return null;
            }
            Type entityType = entity.GetType();

            NHibernate.Metadata.IClassMetadata entityMeta = sessionFactory.GetClassMetadata(entityType);
            if (entityMeta != null)
            {
                return entityMeta.GetIdentifier(entity, EntityMode.Map);
            }
            else
            {
                return null;
            }
        }
		private static Expression GetIdentifier(ISessionFactory sessionFactory, Expression expression)
		{
			var classMetadata = sessionFactory.GetClassMetadata(expression.Type);
			if (classMetadata == null)
				return Expression.Constant(null);
			
			return ConvertToObject(Expression.PropertyOrField(expression, classMetadata.IdentifierPropertyName));
		}
		static Expression GetIdentifier(ISessionFactory sessionFactory, IEnumerable<ExpressionHolder> expressions, ExpressionHolder e)
		{
			foreach (var holders in expressions)
			{
				if (holders.Tuple == e.Tuple)
				{
					var memberExpression = holders.Expression as MemberExpression;
					if (memberExpression != null)
					{
						var expression = memberExpression.Expression;
						var classMetadata = sessionFactory.GetClassMetadata(expression.Type);
						if (classMetadata != null)
						{
							return ConvertToObject(Expression.PropertyOrField(expression, classMetadata.IdentifierPropertyName));
						}
					}
				}
			}
			return Expression.Constant(null);
		}
		private static Expression GetIdentifier(ISessionFactory sessionFactory, Expression expression)
		{
			var classMetadata = sessionFactory.GetClassMetadata(expression.Type);
			if (classMetadata == null)
				return Expression.Constant(null);

            var propertyName=classMetadata.IdentifierPropertyName;
            NHibernate.Type.EmbeddedComponentType componentType;
            if (propertyName == null && (componentType=classMetadata.IdentifierType as NHibernate.Type.EmbeddedComponentType)!=null)
            {
                //The identifier is an embedded composite key. We only need one property from it for a null check
                propertyName = componentType.PropertyNames.First();
            }

            return ConvertToObject(Expression.PropertyOrField(expression, propertyName));
		}