nfplee
nfplee

Reputation: 7997

Fluent NHibernate - HasOne With Where Clause

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.

Upvotes: 1

Views: 1830

Answers (2)

VARAK
VARAK

Reputation: 845

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.

Upvotes: 0

Ian Nelson
Ian Nelson

Reputation: 58783

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/

Upvotes: 2

Related Questions