views:

185

answers:

2

I have Linq to Entity query like you can see below I am using it five times in my code, everything that change is where clause. is it possible to create a method and pass just where values, not to write all 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

                                 };
+1  A: 

Write a base 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 function one

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);
}

....

Gregoire
Nice solution, with one adjustment: Don't return IEnumerable, but rather IQueryable. Otherwise it will fall back to using Linq-to-objects and do the filtering in memory.
Anders Abel
@Anders Abel: thanks for the tip
Gregoire
Ok when I am trying to use this way I'm getting the error. Instance argument cannot convert from 'System.Linq.IQueryable' to System.Collections.Generic.IEnumberable<object>.
GodSmart
+1  A: 

If you write it on the function form, you can do it:

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

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

You can then call it as:

DoQuery(t => t.column5 == Something);
Anders Abel
in this example its also not working underlying everything.
GodSmart
Sorry, I don't have a dev. environment on this computer - I'll try to update it tomorrow when I can test it.
Anders Abel