【问题标题】:Entity Framework 4.1 Linq Contains and StartsWithEntity Framework 4.1 Linq 包含和 StartsWith
【发布时间】:2012-01-12 16:12:02
【问题描述】:

我首先使用实体​​框架代码。我想根据 List 对象从数据库中查询实体。这适用于包含,但我如何将它与 StartsWith 结合使用?

这是我的代码:

List<string> values = new List<string>();
values.Add("A");
values.Add("B");
context.Customer.Where(c => values.Contains(c.Name)).ToList();

如何查询所有以 A 或 B 开头的客户?

【问题讨论】:

    标签: c# .net linq entity-framework linq-to-entities


    【解决方案1】:

    这应该在内存中工作,但我不确定它是否可以被 EF 翻译成 SQL:

    context.Customer.Where(c => values.Any(s => c.Name.StartsWith(s))).ToList();
    

    【讨论】:

    • fyi 遗憾地更新了 ef core 这将在本地进行评估]) select [text] => Any()}' 无法翻译,将在本地进行评估。
    • @AnthonyJohnston This may be related
    【解决方案2】:

    您不需要将它与 StartsWith 组合,因为如果它以 A 或 B 开头,那么它显然包含 A 或 B。它不能以 A 或 B 开头并且不包含 A 或 B。

    所以只需使用 StartsWith 而不是 Contains。

    context.Customer.Where(c => c.StartsWith("A") || c.StartsWith("B")).ToList(); 
    

    【讨论】:

    • 我没有使用 String.Contains() 而是 List.Contains()。您的解决方案有效但不是动态的。例如。查询 A-K。
    • @LuckyStrike - 我建议如果您有这样的要求,请将它们包含在您的问题中。否则你只会浪费每个人的时间,拒绝他们不知道不是你想要的解决方案。
    【解决方案3】:

    您可以尝试以这种方式组合这两个功能:

    IQueryable<Customer> result = (from C in context.Customerwhere C.Name.StartsWith("B") && values.Contains(C.Name));
    

    【讨论】:

    • 您在 context.Customerwhere 中的 C 中缺少一个空格,它应该来自 context.Customer where 中的 C
    猜你喜欢
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2011-09-19
    • 2011-08-15
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 2012-11-30
    相关资源
    最近更新 更多