是否可以将EF Core查询与LINQ和动态字符串查询混合在一起?

时间:2018-02-27 17:49:03

标签: c# entity-framework-core ef-core-2.0

我希望能够在LINQ中编写大部分查询,然后将WHERE子句写为字符串,就像动态查询一样。如下所示:

var query = from part in _context.CurrentInventory

query.Where = "part.PartNumber LIKE '%a%' OR part.PartNumber LIKE '%b%'

原因是因为WHERE可能变得非常大并且使用EF.Functions.LikeContains确实会降低查询速度。

我可以动态地构建整个事物并只执行字符串,但我希望避免这种情况。

1 个答案:

答案 0 :(得分:1)

您可以使用System.Linq.Dynamic以前的工作<{3}}

    Install-Package System.Linq.Dynamic

查询

   query.Where = "part.PartNumber LIKE '%a%' OR part.PartNumber LIKE '%b%'

可以重写为:

    query.Where ("part.PartNumber.Contains(@0) or part.PartNumber.Contains(@1)","a" ,"b")

based on

的工作示例

<强>更新

我使用动态Linq和EntityFramework

      using (var context = new NorthwindEntities())
        {
            var customers = context.Customers.Where("ContactName.Contains(@0) or ContactName.Contains(@1)", "Maria","Carine").ToList();
            Console.WriteLine(customers.Count);
        }

生成的Sql(从sql profiler看到)是:

    SELECT 
        [Extent1].[CustomerID] AS [CustomerID], 
        [Extent1].[CompanyName] AS [CompanyName], 
        [Extent1].[ContactName] AS [ContactName], 
        [Extent1].[ContactTitle] AS [ContactTitle], 
        [Extent1].[Address] AS [Address], 
        [Extent1].[City] AS [City], 
        [Extent1].[Region] AS [Region], 
        [Extent1].[PostalCode] AS [PostalCode], 
        [Extent1].[Country] AS [Country], 
        [Extent1].[Phone] AS [Phone], 
        [Extent1].[Fax] AS [Fax]
        FROM [dbo].[Customers] AS [Extent1]
     WHERE ([Extent1].[ContactName] LIKE N'%Maria%') OR ([Extent1].[ContactName] LIKE N'%Carine%')

where条件转换为:

     WHERE ([Extent1].[ContactName] LIKE N'%Maria%') OR ([Extent1].[ContactName] LIKE N'%Carine%')