Get table names from Fluent Nhibernate

2019-06-19 02:49发布

问题:

After you have setup your mappings in fluent nhibernate, is there a way of getting the table name for an entity from the class type?

I have read in regular nhiberante you can do something like cfg.GetClassMapping(typeof (Employee)). I would like to do the type of thing to retrieve the database table name.

Is this possible as standard or how would I go about this?

回答1:

The fluent nhibernate way:

var userMetadata = sessionFactory.GetClassMetadata(typeof(SomeEntity)) as NHibernate.Persister.Entity.AbstractEntityPersister;
var cols = userMetadata.KeyColumnNames;
var table = userMetadata.TableName;

where sessionFactory is of type ISessionFactory.



回答2:

Assuming you have done this at some point:

FluentNHibernate.Cfg.FluentConfiguration fluentConfig = FluentNHibernate.Cfg.Fluently.Configure();

Then all you have to do is this:

string tableName = fluentConfig.BuildConfiguration().GetClassMapping(typeof (One of your data entities)).Table.Name;

Worked great in my implementation of a generic "GetAllItems" routine.



回答3:

Hi I'm using this to create Full Text Catalogs on M$ Sql Server, using almost same mechanism of FluentNhibernate mapping.

From Configuration I get a list of persistentClasses

this.persistenClasses = configuration.ClassMappings;

Next I search through this list to find my persistenClass class by its Generic type of mapping class

var genericDefinition = mappingClass.BaseType.GetGenericArguments()[0];
var matchedPersistClass = FindPersistedClassFrom(genericDefinition);


        private PersistentClass FindPersistedClassFrom(Type genericDefinition)
        {
            return persistentClasses.FirstOrDefault(x => x.EntityName == genericDefinition.FullName);
        }

So having persistentClass you easily have access to Table Name, properties, db fields, etc.

TableName = matchedPersistClass.Table.Name,


回答4:

cfg.GetClassMapping(typeof(Employee)).Table.Name will also work, and seems to be much simpler.