简体   繁体   中英

NHibernate QueryOver and access=“field” members

Let's say I have a class that looks like this:

public class User : Entity{
   public virtual string FullName{get;set;}
}

where Entity is a very simple base class that we use for NHibernate binding:

public class Entity{
   public virtual int ID{
   {
      get{return id;}
   }

   private int id = 0;    
}

If I want to use a QueryOver that includes the ID of the User, how would I accomplish this given that I bind the field like so:

<id name="id" column="UserID" access="field" unsaved-value="0">
            <generator class="identity" />
        </id>

Is there a method that will allow me to access the field in my query over? If I try to use it with the public property, I know that I will run into issues with the property not actually being bound in the HBM.

Given that HQL can handle this sort of situation, I am curious if QueryOver can as well.

As an aside: I would argue that ID should be a public property without a backing field and have a private setter, but I am wary of making such a sweeping change (this pattern is everywhere in our domain).

QueryOver (and LINQ) uses lambda expressions to reference property names, which means the visibility rules are the C# visibility rules. HQL and ICriteria use strings, so there's no limitation.

If it's 'only' the ID property, you might find it possible to have a method that takes a lambda-expression for your ID property, and returns an ICriterion (which QueryOver allows you to add to your query).

Alternatively, if you can put your queries inside the appropriate class (or as an inner-class), then C# syntax should allow you to access the field.

This is a common limitation in APIs that use lambda expressions. Here's some thoughts from the FluentNHibernate team, who obviously have the same limitations:

http://wiki.fluentnhibernate.org/Fluent_mapping_private_properties

(My personal preference is to make my queries inner-classes.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM