How to create dynamic NHibernate mappings without

2019-03-02 06:51发布

问题:

I'm working on a dynamic application with NHibernate. My goal is to create dynamic entities (both class type and mapping xml file) based on some data. For example suppose I want to create a Person entity dynamically in runtime and on the fly.

I use Reflection.Emit to generate class type dynamically. For creating mapping dynamically I used Ayende's code.. But unfortunately this code does not work because mappings does not have Classes property. I tried to code as same as codes of Castle ActiveRecord and Fluent NHibernate but they generate HBM XML files. As I don't want to generate/create mapping files so I can not use these solutions.

Is there any way that like Ayende's solution not to be forced to generate HBM XML mapping files and just doing everything dynamically and in memory?

回答1:

NHibernate 3.2 has a mapping-by-code layer that does what you want.

I'm not sure if dynamic classes will work, but it doesn't hurt to try.



回答2:

fluentnhibernate creates hbm in memory just to feed them to nhibernate. fluentnhibernate has the nice automapping feature with costumizable conventions, perfect for this situation. Also in FNH 2.0 they are working to skip hbm for better performance, but normally you'll never see the mappings outside memory.

Sample:

Assembly assembly = GetDynamicallyCreatedTypesAssembly();

ISessionFactory sf = Fluently.Configure()
    .Database(...)
    .Mappings(m => m.AutoMappings.Add(AutoMap.Assembly(assembly)))
    .BuildSessionFactory();