如何使用Express.call方法创建(谓词)从DataTable获取数据

时间:2016-12-22 10:12:50

标签: c# asp.net linq

我在Home Controller中有一个DataTable,如下所示:

public DataTable GetTable()
{
    DataTable table = new DataTable();
    table.Columns.Add("Dosage", typeof(int));
    table.Columns.Add("Drug", typeof(string));
    table.Columns.Add("Patient", typeof(Info));
    table.Columns.Add("Date", typeof(DateTime));

    table.Rows.Add(25, "Indocin", new Info("India"), DateTime.Now);
    table.Rows.Add(50, "Enebrel", new Info("UK"), DateTime.Now);
    table.Rows.Add(10, "Hydralazine", new Info("Bhutan"), DateTime.Now);
    table.Rows.Add(21, "Combivent", new Info("India"), DateTime.Now);
    table.Rows.Add(100, "Dilantin", new Info("GreenLand"), DateTime.Now);
    return table;
}

信息类如下

public class Info
{
    public string Address { get; set; }
    public Info(string Add) {
        this.Address = Add;
    }
}

现在,我想基于地址字段进行过滤操作,即Patient.Address

此处,患者是Info类的对象

我需要形成条件,以便获取数据。

我正在使用Express.call方法

形成条件
private static MethodCallExpression GetFieldCallExpression(Expression memExp, Type ColumnType, string ColumnName)
        {
            MethodInfo method = typeof(DataRowExtensions).GetMethods().Where(m => m.Name == "Field" && m.IsGenericMethod && m.GetParameters().Count() == 2 && m.GetParameters()[1].ParameterType == typeof(string)).FirstOrDefault();
            var genericWrapper = method.MakeGenericMethod(new Type[] { ColumnType });
            var toLowerMethodCall = Expression.Call(
                 null,
                 genericWrapper,
                 memExp,
                 Expression.Constant(ColumnName, ColumnName.GetType())
                 );
            return toLowerMethodCall;
        }

这里,memExp - DataRow的实例 columnName - Patient.Address columnType - string

Predicate is formed as like this

它收到了消息,

“列'Patient.Address'不属于表。”

我犯了哪里错误

1 个答案:

答案 0 :(得分:0)

DataRow值访问器仅支持“顶级”列名称(如样本中的“剂量”,“药物”,“患者”等)。为了实现目标,您必须手动分割路径并生成访问者。

例如,“Patient.Address”的样本访问者应为dr.Field<Info>("Patient").Address或换句话说:

var value1 = dr.Field<Info>("Patient");
var value2 = value1.Address;
...
return value2;

以下是相同的实现:

private static Expression GetFieldValueExpression(Expression source, Type columnType, string memberPath)
{
    var memberNames = memberPath.Split('.');
    Expression value = Expression.Call(
        typeof(DataRowExtensions), "Field", new Type[] { columnType },
        source, Expression.Constant(memberNames[0]));
    for (int i = 1; i < memberNames.Length; i++)
        value = Expression.PropertyOrField(value, memberNames[i]);
    return value;
}