Get / set property by expression

An attempt to create a data access component by mapping fields from an oracle database to object properties. I created a base object that takes a type and is called like that ...

public class Document : DataProviderBase<DataObjects.Document> 
{ 
    // code goes here... 
}

This base object has a method called AddMappingthat maps database fields to properties such as this ...

this.AddMapping<int>("ATD_KEY", "Key")

In this case...

  • int is the type of property
  • ATD_KEY - field name in the database
  • Key is the name of the property on DataObjects.Document

The code uses ...

typeof(<TParent>).GetProperty(<property name>)

.. get PropertyInfo, which is used to get and set the property. Although this is great, I would like to add a bit of type safety and lambda expressions to the method AddMapping. I would like to do something like the following ...

this.AddMapping<int>("ATD_KEY", o => o.Key)

.. o , DataProviderBase. , Key int , "Key" , , 1 AddMapping.

? , ?

, , - , , .

+4
2

- :

public void AddMapping<T>(fieldName, Expression<Func<TParent, T>> propExpr)
{
    var memberExpr = (MemberExpression)propExpr.Body;
    PropertyInfo property = (PropertyInfo)memberExpr.Member;
    ...
}
+1

, :

public static PropertyInfo GetProperty<TParent>(Expression<Func<TParent, object>> prop)
{
    var expr = prop.Body;

    if (expr.NodeType == ExpressionType.Convert)
        expr = ((UnaryExpression)expr).Operand;

    if (expr.NodeType == ExpressionType.MemberAccess)
        return ((MemberExpression)expr).Member as PropertyInfo;

    throw new ArgumentException("Invalid lambda", "prop");
}

public void AddMapping<TParent>(fieldName, Expression<Func<TParent, object>> prop)
{
    AddMapping(fieldName, GetProperty(prop).Name);
}

, (TParent). , . , .

+1

Source: https://habr.com/ru/post/1546547/


All Articles