如何使用 NHibernate 枚举列名?

发布于 2024-07-17 07:34:54 字数 168 浏览 6 评论 0原文

我有一个带有一堆 [ColumnName("foo")] NHibernate 属性的类。 有没有一种简单的方法可以要求 NHibernate 列出给定类的所有 ColumnName?

听起来应该很简单,但我只是没有在 NHibernate 文档中看到任何类型的检查(或者也许我今天只是盲目的)。

I've got a class with a bunch of [ColumnName("foo")] NHibernate attributes.
Is there an easy way to ask NHibernate to list all of the ColumnNames for a given class?

It sounds like it should be really easy but I'm just not seeing any kind of inspection in the NHibernate docs (or maybe I'm just blind today).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

z祗昰~ 2024-07-24 07:34:54

我遇到了同样的问题,但发现 IClassMetadata 没有任何列信息,只有属性类型、名称、标识符和表信息。

对我有用的:

PersistentClass persistentClass = cfg.GetClassMapping(typeof(MyEntity));
Property property = persistentClass.GetProperty(propertyName);
property.ColumnIterator   // <-- the column(s) for the property

I had this same problem, but found IClassMetadata doesn't have any column information, just property types, names, identifier, and table information.

What worked for me:

PersistentClass persistentClass = cfg.GetClassMapping(typeof(MyEntity));
Property property = persistentClass.GetProperty(propertyName);
property.ColumnIterator   // <-- the column(s) for the property
顾忌 2024-07-24 07:34:54

如何获取 NHibernate 映射的实体的数据库列名称:

using System;
using System.Collections.Generic;
using NHibernate;
using NHibernate.Persister.Entity;

namespace Stackoverflow.Example
{
    /// <summary>
    /// NHibernate helper class
    /// </summary>
    /// <remarks>
    /// Assumes you are using NHibernate version 3.1.0.4000 or greater (Not tested on previous versions)
    /// </remarks>
    public class NHibernateHelper
    {
        /// <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 IEnumerable<string> GetPropertyColumnNames(ISessionFactory sessionFactory, object entity)
        {
            Type entityType = entity == null ? null : entity.GetType();

            List<string> columnNameList = null;

            // This has some cool methods and properties so check it out
            var metaData = entityType == null ? null : sessionFactory.GetClassMetadata(entityType.ToString());

            //- metaData validity check ... will be null if provided type is not mapped
            if (metaData != null)
            {
                // This has some even cooler methods and properties so definitely check this out
                var entityPersister = (AbstractEntityPersister) metaData;

                //- how to get the entity's identifier
                //- string entityIdentifier = metaData.IdentifierPropertyName;

                //- Get the database identifier
                //- can have multiple in case of composite keys
                IEnumerable<string> dbIdentifierNameList = entityPersister.KeyColumnNames;

                var propertyNameList = entityPersister.PropertyNames;

                // Adding the database identifier first
                columnNameList = new List<string>(dbIdentifierNameList);
                //- then add properties column names
                foreach (var propertyName in propertyNameList)
                {
                    var columnNameArray = entityPersister.GetPropertyColumnNames(propertyName);
                    columnNameList.AddRange(columnNameArray.Where(columnName => dbIdentifierNameList.Contains(columnName) == false));
                }
            }

            return columnNameList;
        }
    }
}   

用法:

// Get your NHiberate SessionFactory wherever that is in your application
var sessionFactory = NHibernateHelper.SessionFactory;

// Get an entity that you know is mapped by NHibernate
var customer = new Customer();

// Get a list of the database column names for the entity
var columnNames = 
        Stackoverflow.Example.NHibernateHelper.GetPropertyColumnNames( sessionFactory, customer );

享受这种令人敬畏的荣耀:)

How to get the database column names for an entity mapped by NHibernate:

using System;
using System.Collections.Generic;
using NHibernate;
using NHibernate.Persister.Entity;

namespace Stackoverflow.Example
{
    /// <summary>
    /// NHibernate helper class
    /// </summary>
    /// <remarks>
    /// Assumes you are using NHibernate version 3.1.0.4000 or greater (Not tested on previous versions)
    /// </remarks>
    public class NHibernateHelper
    {
        /// <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 IEnumerable<string> GetPropertyColumnNames(ISessionFactory sessionFactory, object entity)
        {
            Type entityType = entity == null ? null : entity.GetType();

            List<string> columnNameList = null;

            // This has some cool methods and properties so check it out
            var metaData = entityType == null ? null : sessionFactory.GetClassMetadata(entityType.ToString());

            //- metaData validity check ... will be null if provided type is not mapped
            if (metaData != null)
            {
                // This has some even cooler methods and properties so definitely check this out
                var entityPersister = (AbstractEntityPersister) metaData;

                //- how to get the entity's identifier
                //- string entityIdentifier = metaData.IdentifierPropertyName;

                //- Get the database identifier
                //- can have multiple in case of composite keys
                IEnumerable<string> dbIdentifierNameList = entityPersister.KeyColumnNames;

                var propertyNameList = entityPersister.PropertyNames;

                // Adding the database identifier first
                columnNameList = new List<string>(dbIdentifierNameList);
                //- then add properties column names
                foreach (var propertyName in propertyNameList)
                {
                    var columnNameArray = entityPersister.GetPropertyColumnNames(propertyName);
                    columnNameList.AddRange(columnNameArray.Where(columnName => dbIdentifierNameList.Contains(columnName) == false));
                }
            }

            return columnNameList;
        }
    }
}   

Usage:

// Get your NHiberate SessionFactory wherever that is in your application
var sessionFactory = NHibernateHelper.SessionFactory;

// Get an entity that you know is mapped by NHibernate
var customer = new Customer();

// Get a list of the database column names for the entity
var columnNames = 
        Stackoverflow.Example.NHibernateHelper.GetPropertyColumnNames( sessionFactory, customer );

Bask in the glory of this awesomeness :)

梦回梦里 2024-07-24 07:34:54

使用 LINQ 和反射:

var columns = typeof(TheClass).GetProperties()
    .Where(property => property.GetCustomAttributes(typeof(ColumnNameAttribute), false).Count > 0)
    .Select(property => property.Name);

Use LINQ and reflection:

var columns = typeof(TheClass).GetProperties()
    .Where(property => property.GetCustomAttributes(typeof(ColumnNameAttribute), false).Count > 0)
    .Select(property => property.Name);
梦初启 2024-07-24 07:34:54

使用 NHibernate 的元数据

// get an instance to the metadata 
IClassMetadata metadata = sessionfactory.GetClassMetadata(typeof(MyEntity));

// use properties and methods from the metadata:
// metadata.PropertyNames
// metadata.PropertyTypes
// metadata.GetIdentifier()
// and more

// or get the metadata for all classes at once
IDictionary allClassMetaData = factory.GetAllClassMetadata();
metadata = allClassMetaData[typeof(MyEntity)];

您可以获得 NHibernate 实际知道的内容,而与它的定义方式无关; 使用属性、xml 映射或 FluentNHibernate。 这使得它比自己使用反射更稳定、更可靠。

Use NHibernate's Metadata

// get an instance to the metadata 
IClassMetadata metadata = sessionfactory.GetClassMetadata(typeof(MyEntity));

// use properties and methods from the metadata:
// metadata.PropertyNames
// metadata.PropertyTypes
// metadata.GetIdentifier()
// and more

// or get the metadata for all classes at once
IDictionary allClassMetaData = factory.GetAllClassMetadata();
metadata = allClassMetaData[typeof(MyEntity)];

You get what NHibernate actually knows, independent of how it is defined; using attributes, xml mappings or FluentNHibernate. This makes it more stable and more reliable than using reflection on your own.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文