Fluent NHibernate - Mapping entities from multiple assemblies

回眸只為那壹抹淺笑 提交于 2019-12-13 14:07:16

问题


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)

回答1:


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)



回答2:


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);
                }
            }
        }



回答3:


It seems you may only call AddEntityAssembly once, read here for a discussion.

I would guess it overrides your previous line.




回答4:


You could do something similar to what sharp does.

foreach (var assemblyName in mappingAssemblies)
{
    Assembly assembly = Assembly.Load(assemblyName);
    m.FluentMappings.AddFromAssembly(assembly );
}

That works for me at least.



来源:https://stackoverflow.com/questions/1520758/fluent-nhibernate-mapping-entities-from-multiple-assemblies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!