如何使用 Fluent NHibernate 和多个数据库识别特定实体的会话工厂
问题来自 Fluent NHibernate + 多个数据库(无需点击此链接,应该有这里有足够的背景)。
我的问题是这样的:
我正在使用 Fluent NHibernate。我的应用程序使用多个数据库。每个数据库都有自己的注册(映射)实体。结果是拥有多个会话工厂,每个会话工厂都与一个数据库相关,并且每个“包含”自己的一组映射实体。
为了加载实体,我创建了一个通用工厂类,它提供了一些可用于任何注册实体(在任何数据库中)的标准加载方法。问题是:加载方法需要为我正忙于处理的实体类使用正确的会话工厂。我如何确定需要使用哪个会话工厂?我“手头上”有所有会话工厂(并按数据库名称索引),我只需要一种方法,了解我要加载的实体类型,选择要使用的正确会话工厂。
例如:
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;
}
GetSessionFactory(boType) 需要做什么?
感谢您的阅读!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我首先查看 ISessionFactory.GetClassMetaData 方法。
如果您可以维护 ISessionFactory 实例的列表,则可以枚举它们,直到找到包含您的类型 boType 的元数据的实例。
我从未使用过它,也没有手头的引用,但我希望它返回 null 或在它无法识别该类型时引发异常。如果您获得元数据的值且没有错误,那么这就是您的会话工厂。
祝你好运
,尼尔。
I'd start with looking at the ISessionFactory.GetClassMetaData method.
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.