Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically referencing properties in NHibernate?

I'm currently cutting my teeth on nHibernate and had a question with regards to dynamically accessing properties in my persistent objects.

I have the following class in my Domain:

public class Locations {
    public virtual string CountryCode;
    public virtual string CountryName;
}

Now, assuming I have a reference to a Locations object, is there any way for me to do something like this?

Locations myCountry = new LocationsRepository().GetByCountryCode("US");
myCountry.Set("CountryName", "U.S.A.");

instead of having to do :

myCountry.CountryName = "U.S.A."

Without reflection?

like image 487
Mr. S Avatar asked Dec 02 '25 14:12

Mr. S


1 Answers

If your goal of avoiding reflection is to increase performance, then a simple solution is to hard-code the functionality with all the properties like this:

public class Locations {
    public virtual string CountryCode;
    public virtual string CountryName;

    public void Set(string propertyName, string value) {
        if (propertyName == "CountryCode") this.CountryCode = value;
        else if (propertyName == "CountryName") this.CountryName = value;
        else throw new ArgumentException("Unrecognized property '" + propertyName + "'");
    }
}

You could easily make this approach tenable by using T4 templates to generate the Set methods for all of your domain classes programmatically. In fact, we do similar kinds of things in our own code-base, using T4 templates to generate adapters and serializers to avoid the cost of reflection at run-time while gaining the flexibility of reflection for code-generation at compile-time.

like image 179
mellamokb Avatar answered Dec 04 '25 04:12

mellamokb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!