我使用 FluentNhibernate,并且当关联引用映射为 NHibernate 时,我看到 NHibernate 执行许多查询NotFound.Ignore()
.
由于我的遗留数据库的引用完整性有点糟糕,我想知道是否有解决方法或者是否有我可以使用的替代映射。
Example:
//no query when loading the entity
References<User>(x => x.User, "UserId").LazyLoad().Nullable();
//performs a hundred queries when I load my entities
References<User>(x => x.User, "UserId").LazyLoad().Nullable().NotFound.Ignore();
不幸的是,这是一个已知问题,NHibernate JIRA 中存在一个问题(https://nhibernate.jira.com/browse/NH-1001)
虽然有一个解决方法,但它并不漂亮。在实体中,您需要执行以下操作:
class Entity {
private int? _userId;
private User user;
public User User
{
get {
if (_userId == null)
return null;
return user;
};
set {
if (value == null)
_userId = null;
else
_userId = value.UserId;
_user = value;
};
}
}
在映射中,您将正常映射引用,但没有 not-found =ignore 设置,但您还映射外键字段:
References<User>(Reveal.Membmer<User>("_user"), "UserId").LazyLoad();
Map(Reveal.Membmer<int?>("_userId")).Nullable().Not.Update().Not.Insert(); // Suppress updates and inserts so that they don't conflict with the mapping of User.
基本上,您让 NHibernate 在 _user 字段上正常运行,然后使用 _userId 字段手动执行 null 检查。这样就可以避免 N+1 选择问题。缺点是它使实体变得复杂并且使查询更难编写。例如,如果您希望能够在 LINQ 查询中使用用户属性,则必须公开内部 _user 字段并使用它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)