Fluent NHibernate - HasOne With Where Clause

混江龙づ霸主 提交于 2019-12-11 05:47:34

问题


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");

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); } }

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.


回答1:


HasOne(x => x.CurrentMembership)
    .Where("Current = 1");

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.

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.




回答2:


Are you sure you mean "HasOne" and not a many-to-one ("References")?

http://jagregory.com/writings/i-think-you-mean-a-many-to-one-sir/



来源:https://stackoverflow.com/questions/7176214/fluent-nhibernate-hasone-with-where-clause

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