C# 使用linq构建多个where子句
我正在用EntityFrameWorkCore和Sqlite编写一个dotnet core MVC web应用程序 我试图基于查询字符串提供的数据构建一个动态where子句,查询字符串中可能传递了多个键值对,我想将它们全部添加到where子句,我想我可以这样做,但它会返回初始查询中的所有行C# 使用linq构建多个where子句,c#,linq,sqlite,entity-framework-6,C#,Linq,Sqlite,Entity Framework 6,我正在用EntityFrameWorkCore和Sqlite编写一个dotnet core MVC web应用程序 我试图基于查询字符串提供的数据构建一个动态where子句,查询字符串中可能传递了多个键值对,我想将它们全部添加到where子句,我想我可以这样做,但它会返回初始查询中的所有行 public class Application { public Application() { Data = new List<Data>(); }
public class Application
{
public Application()
{
Data = new List<Data>();
}
public int ApplicationId { get; set; }
[Required][Display(Name = "Application Name")]
public string Name { get; set; }
public Guid PublicKey { get; set; }
public Guid PrivateKey { get; set; }
public bool HideFromSearch { get; set; }
public DateTime InsertDate { get; set; }
public List<Data> Data { get; set; }
}
public class Data
{
public Data()
{
DataItems = new List<DataItem>();
}
public int DataId { get; set; }
public int ApplicationId { get; set; }
public DateTime InsertDate { get; set; }
public List<DataItem> DataItems { get; set; }
}
public class DataItem
{
public int DataItemId { get; set; }
public int DataId { get; set; }
public string PropertyName { get; set; }
public string PropertyValue { get; set; }
}
我在一个项目中使用了动态Linq,并认为它是解决复杂动态查询所需要的
您是否了解将在RequestQuerytry LinqKit中查询的所有列,您可以在其中构建动态谓词并将其应用于where子句。它是开源的。很难相信添加的
Where
条件不会减少返回的应用程序的数量。你的意思是想过滤包含的数据项吗?是的,我只想返回与后续查询匹配的数据项。这是经常出现的过滤Include
问题。它不受支持。
var apps = context.Applications.Include(app => app.Data).ThenInclude(data => data.DataItems).Where(app => app.PublicKey == publicKey);
foreach (var item in Request.Query)
{
apps = apps.Where(q => q.Data.Any(r => r.DataItems.Any(s => s.PropertyName == item.Key && s.PropertyValue == item.Value[0] )));
}