开发者

Linq to Entity Dynamic where clause

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开发者_C百科 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

                                 };


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

....


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜