Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent NHibernate - Mapping entities from multiple assemblies

Is it possible to map entities from multiple assemblies in Fluent NHibernate?

I tried

AutoPersistenceModel
.MapEntitiesFromAssemblyOf<Class1>()
.AddEntityAssembly(assembly)

But it only loads entities from 'assembly' and not from parent assembly of Class1.

EDIT. I figured it out. I had to update Fluent NHibernate to version 1.0, where you can do it like this:

AutoMap
.AssemblyOf<Class1>()
.AddEntityAssembly(typeof(UserEntity).Assembly)
like image 908
Egor Pavlikhin Avatar asked Feb 05 '26 13:02

Egor Pavlikhin


2 Answers

I figured it out. I had to update Fluent NHibernate to version 1.0, where you can do it like this:

AutoMap
.AssemblyOf<Class1>()
.AddEntityAssembly(typeof(UserEntity).Assembly)
like image 135
Egor Pavlikhin Avatar answered Feb 07 '26 02:02

Egor Pavlikhin


We succesfully map entities from multiple assemblies by using NHibernate.Cfg.Configuration.AddAssembly() multiple times. A code snippet is below. As you can see, we inspect all assemblies in the current domain and any assembly that has our own custom attribute called "HibernatePersistenceAssembly" on it gets added. We created this attribute simply so that this loop would know which assemblies have NHibernate entities in them, but you could use whatever scheme you want to decide which assemblies to add including simply hardwiring them if you wanted to.

In AssemblyInfo.cs for each Assembly that has NHibernate entities in it:

[assembly: HibernatePersistenceAssembly()]

And then in our Hibernate Utilities class:


        public NHibernate.Cfg.Configuration ReloadConfiguration()
        {
            configuration = new NHibernate.Cfg.Configuration();
            configuration.Configure();
            ConfigureConnectionString();
            ConfigureAssemblies();

            return configuration;
        }

        private void ConfigureAssemblies()
        {
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (object attribute in assembly.GetCustomAttributes(true))
                {
                    if (attribute is HibernatePersistenceAssembly)
                        configuration.AddAssembly(assembly);
                }
            }
        }
like image 22
Clay Fowler Avatar answered Feb 07 '26 02:02

Clay Fowler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!