【问题标题】:No property or field exists in type dynamic class类型动态类中不存在属性或字段
【发布时间】:2015-10-18 05:25:29
【问题描述】:

我正在尝试为我的报告创建动态查询。 我的查询返回使用 .select(selectstringquery) 和 .where(wherestringquery). 的 IEnumerable

string   selectstringquery = "student_fname, student_lname"
string wherestringquery = "student_lname='joe'";

var test = (from s in students).select(selectstringquery).where(wherestringquery); //this works well

wherestringquery = "student_isRegistered=false";
var test = (from s in students).select(selectstringquery).where(wherestringquery) //this fails coz isRegistered is a valid proerpty but not is NOT in select query. 

它抛出一个错误没有属性或字段'student_isRegistered'存在 在类型'f__AnonymousType337`14'

但是如果我将 where 放入 linq 时它可以工作

例如

 (from s in students
where s_isRegistered=false).select(selectstringquery) 

如何在不将列包含在选择查询中的情况下使其工作?原因是我想在所有报告中重复使用该查询,而有些则不需要该过滤器。

另外,在这种情况下,我正在使用

“否则” 确定 wherestringquery 是否不为空,否则我使用与上面完全相同的查询,但没有 .where(wherestringquery)。即使 wherestringquery 为空,是否有可能使用 .where() 的方法?我试过写 .where(true) 但它抛出异常。

谢谢。

【问题讨论】:

  • 您是否尝试在选择之前添加 where ?,var test = (from s in students).where(wherestringquery).select(selectstringquery)
  • 好的。这行得通。 :) 动态在哪里怎么样?有没有其他方法可以只使用 1 个查询,但 where 字符串有时为空?
  • 我认为没有办法做到这一点,一个技巧是你总是可以有一个 where 语句,例如1=1。使用 if else 也没有坏处。

标签: c# linq dynamic predicate anonymous


【解决方案1】:

您试图在通过 select 子句选择较少的列后应用 where 子句。只需在选择列之前执行 where 例如

var test = (from s in students).where(wherestringquery).select(selectstringquery); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    相关资源
    最近更新 更多