【问题标题】:Linq to Entity Dynamic where clauseLinq to Entity Dynamic where 子句
【发布时间】:2010-05-11 02:21:02
【问题描述】:

我有 Linq to Entity 查询,就像你在下面看到的那样,我在我的代码中使用了五次,所有变化都是 where 子句。是否可以创建一个方法并仅传递 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

                                 };

【问题讨论】:

  • 你没有导航属性吗?

标签: linq-to-entities


【解决方案1】:

写一个基函数

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

....

【讨论】:

  • 不错的解决方案,只需进行一次调整:不要返回 IEnumerable,而是返回 IQueryable。否则它将回退到使用 Linq-to-objects 并在内存中进行过滤。
  • 好的,当我尝试使用这种方式时,我得到了错误。实例参数无法从 'System.Linq.IQueryable' 转换为 System.Collections.Generic.IEnumberable.
【解决方案2】:

如果写在函数表上,可以这样做:

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

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

你可以这样称呼它:

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

【讨论】:

  • 对不起,我没有开发者。这台计算机上的环境 - 明天我可以测试时尝试更新它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2014-12-05
相关资源
最近更新 更多