【问题标题】:SQL Like clause in LINQ [duplicate]LINQ中的SQL Like子句[重复]
【发布时间】:2021-12-19 16:34:15
【问题描述】:

我正在尝试将 SQL Server 存储过程迁移到 LINQ,但当我有一个需要在主表中找到的部分匹配列表时遇到了困难。

简而言之,我需要将以下 SQL 复制到 LINQ 中。任何帮助将不胜感激。

SQL

DECLARE @filters TABLE([filter] NVARCHAR(20))

INSERT INTO @filters VALUES ('Den%');
INSERT INTO @filters VALUES ('%zil');
INSERT INTO @filters VALUES ('%la%');

SELECT c.*  
FROM [Northwind].[dbo].[Customers] c
INNER JOIN @filters f ON c.Country LIKE (f.filter)
ORDER BY Country

C#

var filters = new string[] { "Den*", "*zil", "*la*" };

var results = from C in ctx.Customers
              join f in filters c.Country like f
              Select new 
                     {
                         c.CustomerId,
                         c.Country
                     };

【问题讨论】:

  • 我假设您意识到 country = 'Denlazil" 的行将返回 3 行?

标签: c# linq .net-core entity-framework-core


【解决方案1】:
var result = context.Customers.AsNoTracking()
                    .Include(x => x.Country)
                    .Where(x => x.Country.Contains("la") || x.Country.Startwith("Den") || x.Country.EndWith("zil"))

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

您可以使用 EF Core 中提供的 EF.Functions.Like() 方法。 我们在字符串中使用% 表示LIKE,而不是*。 所以你的查询看起来像:

var filters = new string[] { "Den%", "%zil", "%la%" };

var result = context.Customers.AsNoTracking()
                 .Where(c => filters.Any(f => EF.Functions.Like(c.Country, f)))
                 .OrderBy(c => c.Country)
                 .ToList();

如果您只有一个过滤器,那么您的查询将简化为:-

var filter = "%la%";

var result = context.Customers.AsNoTracking()
                 .Where(c => EF.Functions.Like(c.Country, filter))
                 .OrderBy(c => c.Country)
                 .ToList();

【讨论】:

    【解决方案3】:

    你可以使用以下示例:

    var result = context.Customers.AsNoTracking()
                        .Include(x => x.Country)
                        .Where(x => x.Country.Contains("Den"));
    

    作为这个例子:

    https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.contains?view=net-5.0

    【讨论】:

      猜你喜欢
      • 2017-08-30
      • 2012-12-05
      • 1970-01-01
      • 2014-02-01
      • 2013-11-25
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多