Dynamic column name in where clause. Entity Framework

后端 未结 4 1790
遥遥无期
遥遥无期 2021-01-23 01:06

I want to dynamically place column name in my select-query. How I can do this?

public IEnumerable MyTable MySelect(string colName, string param)
{
  using (MyEnt         


        
相关标签:
4条回答
  • 2021-01-23 01:33

    have you tried 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 is an example.

    PS: I haven't compiled the code so might give error.

    0 讨论(0)
  • 2021-01-23 01:41

    use Expression(Of Func(Of TableName, Boolean)) as input parameter to your method

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

    then you can call it as below:

        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
    
    0 讨论(0)
  • 2021-01-23 01:46

    Using dynamic 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;
      }
    }
    
    0 讨论(0)
  • 2021-01-23 01:55

    Have a look at the Dynamic Linq library and ScottGu's how to library here - it allows for dynamic filtering, sorting etc.

    0 讨论(0)
提交回复
热议问题