Linq to Entity Dynamic where子句

时间:2010-05-10 18:00:45

标签: linq-to-entities

我有Linq to Entity查询,就像你在下面看到我在我的代码中使用它五次,所有改变的是where子句。是否可以创建一个方法并传递值,而不是将所有代码写入五次。谢谢

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

答案 0 :(得分:3)

编写基本功能

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

然后功能一个

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

...

答案 1 :(得分:1)

如果你在功能表上写下它,你可以这样做:

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

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

然后您可以将其称为:

DoQuery(t => t.column5 == Something);
相关问题