1

我想在我的选择查询中动态放置列名。我怎么能做到这一点?

public IEnumerable MyTable MySelect(string colName, string param)
{
  using (MyEntities db = new MyEntities ())
  {
     var query = from res in db.MyTable
     where res.colName.Contains(param)
     select res;
     return query;
  }
}
4

4 回答 4

2

你试过res.Field<string>(colName)吗?

public IEnumerable MySelect(string colName, string param)
{
  using (MyEntities db = new MyEntities ())
  {
     var query = from res in db.MyTable.AsEnumerable()
     where res.Field<string>(colName).Contains(param)
     select res;
     return query;
  }
}

是一个例子。

PS:我还没有编译代码,所以可能会出错。

于 2012-09-14T09:55:39.787 回答
2

使用动态 linq:

using System.Linq.Dynamic;

public IEnumerable MyTable MySelect(string colName, string param)
{
  using (MyEntities db = new MyEntities ())
  {
     var query = db.MyTable.Where($"{colName} LIKE %{param}%");
     return query;
  }
}
于 2018-12-18T09:43:56.163 回答
0

看看Dynamic Linq library和 ScottGu 的how to library here - 它允许动态过滤、排序等。

于 2012-09-14T09:45:14.757 回答
0

用作Expression(Of Func(Of TableName, Boolean))方法的输入参数

    Public Function SelectFirstOrDefault(ByVal filterExpr As Expression(Of Func(Of T, Boolean))) As T 
    Return _dbContext.Set(Of T).FirstOrDefault(filterExpr)
End Function

那么你可以如下调用它:

    Public Function Select() As MyTypeInfo
    dim expr = New Expression(Of Func(Of TableNameClass, Object))() {Function(x) x.Code, Function(x) x.LastModifiedDate, Function(x) x.Title}
    SelectFirstOrDefault(expr)
End Function
于 2014-06-25T07:06:46.507 回答