How to identify a particular entity's Session Factory with Fluent NHibernate and Multiple Databases

天大地大妈咪最大 提交于 2019-12-05 22:45:45

问题


Question follows on from Fluent NHibernate + multiple databases (no need to follow this link,there should be enough background here).

My problem is this:

I'm using Fluent NHibernate. My application uses multiple databases. Each database has its own entities registered (mapped) against it. The result is that have multiple Session Factories, each one relating to a single DB, and each 'containing' its own set of mapped entities.

For loading entities I've created a generic Factory class that provides some standard load methods usable for any registered entity (in any DB). The problem is: The load methods need to use the correct session factory for the entity class I'm busy dealing with. How would I determine which session factory I need to use? I have all the Session Factories 'on hand' (and indexed by database name), I just need a way, knowing just the type of Entity I'm about to load, of choosing the right Session Factory to use.

For example:

public IBaseBusinessObject CreatePopulatedInstance(Type boType, Guid instanceKey)
{
  IBaseBusinessObject result = null;
  ISessionFactory sessionFactory = GetSessionFactory(boType);
  using (ISession session = sessionFactory.OpenSession())
  {
    using (session.BeginTransaction())
    {
      result = (IBaseBusinessObject)session.Get(boType, instanceKey);
    }
  }
  return result;
}

What needs to go on in GetSessionFactory(boType) ?

Thanks for reading!


回答1:


I'd start with looking at the ISessionFactory.GetClassMetaData method.

IClassMetadata metadata = sessionfactory.GetClassMetadata(boType); 

If you can maintain a list of your ISessionFactory instances, you can enumerate your way through them until you find the one which has metadata for your type boType.

I've never used it and don't have my references to hand, but I'd expect it to either return null or raise an exception if it doesn't recognise the type. If you get a value for metadata without an error, then that's your session factory.

Good luck

Neil.



来源:https://stackoverflow.com/questions/2698503/how-to-identify-a-particular-entitys-session-factory-with-fluent-nhibernate-and

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