流利的NHibernate-HasOne with Where子句 [英] Fluent NHibernate - HasOne With Where Clause
问题描述
使用Fluent NHibernate,我可以说出与我的User类的一对多关系:
with Fluent NHibernate i can map a one to many relationship against my User class by saying:
HasMany(x => x.Membership)
.KeyColumn("UserID")
.Where("Deleted = 0");
这按预期方式工作,因为它仅获取尚未删除的成员资格记录.不说我有一个名为最新会员资格"的字段,我知道这将为每个用户返回一条记录,我想说:
This works as expected that it only grabs the Membership records which have not been deleted. No say i have a field called Latest against the Membership where i know this would return one record per user, i'd like to be able to say:
HasOne(x => x.CurrentMembership)
.Where("Current = 1");
但是没有Where方法.我知道我可以这样说:
But there is no Where method. I know i could do this in code by saying:
public virtual Membership CurrentMembership
{ get { return Membership.Single(m => m.Current); } }
但是,这不允许我对此属性执行LINQ查询.过去,我只是接受这作为限制,但是从性能方面来看,它确实开始对我产生影响.
But this doesn't allow me to do LINQ queries against this property. I'd just accepted this as a limitation in the past but it really is starting to bite me in terms of performance.
如果有人可以提供帮助,我将非常感谢.
I'd really appreciate it if someone could help.
推荐答案
HasOne(x => x.CurrentMembership)
.Where("Current = 1");
如果一个实体与另一个实体具有"HasOne"关系,则它只能链接到一件事,因此Where方法是没有意义的.如果您的代码无意中没有将旧成员资格更新为Current = 0,那么它将有2个CurrentMembership实例可以链接到该实例,您会被搞砸了.
If an entity has a "HasOne" relationship to another, then there is only one thing it can link to so a Where method doesn't make sense. If your code accidentally doesn't update the old membership to have Current=0, then there will be 2 instances of CurrentMembership that it could link to and you'd be pretty screwed.
我认为您的数据库设计有问题.我想实现此效果的最佳方法是在User表上具有CurrentMembershipID,然后可以使用HasOne直接链接到该表.这将减少数据库的开销(您不必在成员资格表上存储当前"列),它将有效地执行您要查找的操作.而且,它避免了用户拥有多个成员身份且当前设置为1的用户.
I think that you have a problem in your database design. The best way that I can think of implementing this is is to have a CurrentMembershipID on your User table and then you can link directly to it with a HasOne. This is less overhead for your database (you don't have to store a Current column on your membership table) and it will effectively do what you're looking for. Also, it avoids a user having more than one membership having current set to 1.
这篇关于流利的NHibernate-HasOne with Where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!