使用linq构建多个where子句

时间:2017-03-30 15:49:32

标签: c# linq sqlite entity-framework-6

我正在使用EntityFrameWorkCore和Sqlite编写一个dotnet核心MVC Web应用程序。

我试图根据查询字符串提供的数据构建动态where子句,可能会在查询字符串中传递多个键值对,我想将它们全部添加到where子句中,我想我可以这样做,但它会返回初始查询中的所有行。

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; }
}

代码

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] )));
}

1 个答案:

答案 0 :(得分:1)

我在一个项目中使用了Dynamic Linq,并且认为它是您正在寻找的解决复杂动态查询的方法。

Scott Guthrie sample

Nuget package