Dynamically referencing properties in NHibernate?

I am now cutting my teeth on nHibernate and asked a question regarding dynamic access to properties in my persistent objects.

I have the following class in mine Domain:

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

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

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

instead of doing:

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

Without reflection?

+3
source share
5 answers

I hate answering my questions on StackOverflow and I appreciate all the answers, but none of them did it for me. After some research, I found that the latest versions of NHibernate offer dynamic models .

, , . , SE HyperDescriptor, Fastmember. , DLR, . FastMember- GetValue SetValue , .

+1

- , , , :

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 + "'");
    }
}

, T4 templates, Set . , , T4 , , .

+1

, " ", (, , ), :

using System.Reflection;

typeof(Locations).GetProperty("CountryName").SetValue(myCountry, "U.S.A.", null);

poof, done.

+1

-, . .NET4, ExpandoObject, .

+1

:

public class Locations 
{
  private Dictionary<string, object> _values;
  public Locations() 
  {
    _values = new Dictionary<string, object>();
  }
  public void Set(string propertyName, object value)
  {
     if(!_values.ContainsKey(propertyName))
        _values.Add(propertyName, value);
     else
        _values[propertyName] = value;
  }
  public object Get(string propertyName)
  {
     return _values.ContainsKey(propertyName) ? _values[propertyName] : null;
  }

  public string CountryCode
  {
     get{ return Get("CountryCode"); }
     set{ Set("CountryCode", value); }
  }
}

Thus, you can access the property without reflection and change it in one method. I have not tested this code, but I hope that this is what you mean by "do not have direct access to the property."

0
source

All Articles