Friends, tell me how to filter the selection from the database. Suppose there is a table, it has 5 fields. The user can make a selection of 1, 3 and 5 fields. Maybe 2 and 5 fields. Not known in advance. How to form a query using LINQ dynamically? If I obviously do not know what the user will choose.

Those. I mean how to form a query of this kind on the fly

var list = dataBase.MyTable.Where(x => x.Field2 == "test").Where(x => x.Field5 =="test-test"); 

    2 answers 2

    Create a model for filtering (the user will fill in the fields for which a sample is needed):

     public class FilterModel { public string FileldOne { get; set; } public int? FileldTwo { get; set; } } 

    Use it like this:

     public class MyEntityService { public IQueryable<Entity> GetEntityByFilter(FilterModel filter) { var result = Context.Entity.AsQueryable(); if (filter!= null) { if (!string.IsNullOrEmpty(filter.FileldOne)) result = result.Where(x => x.FileldOne == filter.FileldOne)); if (filter.FileldTwo.HasValue) result = result.Where(x => x.FileldTwo == filter.FileldTwo); } return result; } } 
    • Should the filtering model contain the same fields as my entity? - Pyrejkee
    • Only fields for which you need a sample, at your discretion. - Ruslan_K
    • Another question, why are you doing one check in the first field, and another in the second? - Pyrejkee
    • Wrong, fixed type on string - Ruslan_K
    • Everything works, thank you! - Pyrejkee

    Compose IQueryable from the fragments you need.

    Instead:

     var instances = await this.Db.Instance .Where(x => x.OwnerID == userID && x.Archieved == archieved) .AsNoTracking() .ToArrayAsync(); 

    Write:

     var instancesQuery = this.Db.Instance .Include(x => x.Product.Collection.Brand) .Include(x => x.PrimaryImage) .Where(x => x.OwnerID == userID); if (something1) { instancesQuery = instancesQuery.Where(x => x.Archieved == archieved); } if (something2) { instancesQuery = instancesQuery.Where(x => x.PrimaryImageID == null); } var instances = await instancesQuery .AsNoTracking() .ToArrayAsync();