Linq to Entity Dynamic where clause

I have a Linq to Entity query as you can see below. I use it five times in my code, all that changes is the where clause. is it possible to create a method and only pass the values ​​instead of writing the whole code five times. thank you

    items = from t1 in _entities.table1
                      join t2 in _entities.Table2 on t1.column1 equals t2.column1
                      join t3 in _entities.Table3 on t1.column2 equals t3.column2
                      join t4 in _entities.Table4 on t1.column3 equals t4.column3

                      where **t1.column5 == Something**
                      select new
                                 {
                                    t1.column7,
                                    t2.column8,                                        
                                    t3.column9,
                                    t4.column10

                                 };

      

+2


a source to share


2 answers


Write a basic function

public IQueryable<Object> Select()
{
   return (from t1 in _entities.table1
                      join t2 in _entities.Table2 on t1.column1 equals t2.column1
                      join t3 in _entities.Table3 on t1.column2 equals t3.column2
                      join t4 in _entities.Table4 on t1.column3 equals t4.column3
                      select new
                                 {
                                    t1.column7,
                                    t2.column8,                                        
                                    t3.column9,
                                    t4.column10,
                                    t1.column5
                                 }).AsQueryable<Object>();
}

      

then execute the function



public IQueryable<Object> SelectWhere1(object condition)
{
    return Select().Where(i=>i.column5==condition);
}

public IQueryable<Object> SelectWhere2(object otherCondition)
{
    return Select().Where(i=>i.column7==otherCondition);
}

      

....

+3


a source


If you write it in function form, you can do this:

DoQuery(Expression<Func<Table1Type, bool> lambda)
{

    return _entities.table1
           // Skipping the joins...
           .Where(lambda)
           .Select(t => new { t1.column7 });
}

      



Then you can call it like:

DoQuery(t => t.column5 == Something);

      

+1


a source







All Articles