【问题标题】:Add Or Condition to Entity in Entity Framework在实体框架中向实体添加或条件
【发布时间】:2010-04-04 01:32:30
【问题描述】:

能否在实体框架中为实体添加“或”条件?例如:

属性 1 ==(1 或 2 或 3)

输入“1 || 2 || 3”或“1,2,3”或“1 or 2 or 3”的值时收到的消息返回此消息:

condition is not compatible with the type of the member

【问题讨论】:

    标签: entity-framework entity-framework-4


    【解决方案1】:

    你需要做的:

    var results = entityCollection.Where(entity => entity.Property1 == 1 || entity.Property1 == 2 || entity.Property1 == 3);
    

    【讨论】:

    • 我害怕那个。我想做的是每次执行对该表的查询时都会发生相同的条件,这样我就不必每次点击表时都编写上面的代码。
    • @Blakewell:将查询放在实用程序类中,以便您可以重用它。
    • @Reed Copsey:你错过了entity =>吗?
    • @Mark:不再是了;)当我犯错和改写太快时会发生这种情况。谢谢。
    • 如果我想在一个循环中连接“或”以获得特定属性怎么办?
    【解决方案2】:

    您还应该检查谓词生成器: http://www.albahari.com/nutshell/predicatebuilder.aspx

    它有点高级,但如果您必须动态链接条件,这是您最好的选择。

    foreach (string keyword in keywords)
      {
        string temp = keyword;
        predicate = predicate.Or (p => p.Description.Contains (temp));
      }
    

    【讨论】:

      【解决方案3】:

      这个没试过,不过你可以试试contains。不确定性能,但代码更小:

      int[] vals = new int[] { 1, 2, 3, 4 };
      var results = entityCollection.Where(entity => vals.Contains(entity.Property1));
      

      【讨论】:

      • Contains 仅在尚未发布的 EF 4 中受支持(它与 .Net 4 一起出现在第 12 个)。 MS 的网站上有一个候选版本。
      • 没想到 - 我已经使用 EF 4 一段时间了,所以这看起来很正常。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2014-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多