where子句中的动态列名。实体框架

时间:2012-09-14 09:40:21

标签: c# asp.net .net entity-framework-4

我想在我的select-query中动态放置列名。我怎么能这样做?

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 个答案:

答案 0 :(得分: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;
  }
}

Here就是一个例子。

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

答案 1 :(得分:1)

使用动态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;
  }
}

答案 2 :(得分:0)

在这里查看Dynamic Linq library和ScottGu的how to library - 它允许动态过滤,排序等。

答案 3 :(得分: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