views:

27

answers:

1

I have a user class that looks something like this

public class User
{
    public virtual int Id { get; set; }

    public virtual long ValueA { get; set; }

    public virtual int? ValueB { get; set; }
}

ValueA is automatically assigned by the system. It is used in a lookup that would map to UserClass. However, if a value for ValueB exists, then it would do the lookup for UserClass in a different way.

Right now the way I handle it is to get the User and then perform a separate lookup each time.

return user.ValueB.HasValue ? Find(user.ValueB.Value) : Find(user.ValueA);

Is there any way to make Fluent NHibernate do this for me so I can have UserClass as a property on the User class instead of having to do the lookup separately? I was thinking of the ComponentMap but I'm not sure how to make it account for the two possible lookup values.

Right now the only other solution I can think of is to wrap each return statement in my UserService class to assign the user level before returning the user, which isn't a solution I want to continue t ouse.

public User Find(long valueA)
{
    // Get the user
    return AssignUserLevel(user);
}

public User AssignUserLevel(User user)
{
    // set the user level of the user
}
A: 

Well, that's a bit of logic that NHibernate cannot handle (ValueB overrides ValueA), but you can get it to use references rather than use Ids to lookup.

public class User
{
    public virtual int Id { get; set; }
    public virtual UserClass ValueA { get; set; }
    public virtual UserClass ValueB { get; set; }
    public virtual UserClass UserClass { get { return ValueB ?? ValueA; } }
}

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("MyUserTable");
        Id(user => user.Id).GeneratedBy.Identity();
        References(user => user.ValueA).Not.Nullable();
        References(user => user.ValueB).Nullable();
    }
}
Chris Kemp
Thanks for the answer Chris. ValueB can be directly mapped to the other class, but ValueA isn't actually a key value. It's just a value thats used in a search in order to find the proper UserClass.
Brandon