hasokeric
9/22/2016 - 2:26 PM

Get Property Name as String

Get Property Name as String

// This lets you get the name of a field as a string.
// When calling BOReader or other things that require string names, the compiler can't 
// validate the field names.
// Now it can! No more shit blowing up because you fat fingered a field name.
// Also, schema changes will make the code fail to compile so you upgrades are simpler!

// Saddly it does require linq.

// <summary>
// Get the name of a static or instance property from a property access lambda.
// </summary>
// <typeparam name="T">Type of the property</typeparam>
// <param name="propertyLambda">lambda expression of the form: '() => Class.Property' or '() => object.Property'</param>
// <returns>The name of the property</returns>
public string GetPropertyName<T>(Expression<Func<T>> propertyLambda){
    var me = propertyLambda.Body as MemberExpression;
    if (me == null)
        throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
    return me.Member.Name;
 }
 
// Usage
var Part = new PartDataSet();
var PartNum = GetPropertyName(() => Part.Part[0].PartNum);
var PartDescription = GetPropertyName(() => Part.Part[0].PartDescription);

var bor = WCFServiceSupport.CreateImpl<BOReaderImpl>((Session)oTrans.Session, ImplBase<BOReaderSvcContract>.UriPath);
var partData = bor.GetRows("Erp:BO:Part", 
    string.Format("{0}='SuperPart'", PartNum), 
    string.Format("{0},{1}", PartNum, PartDescription));