I need some sample code for my project. I am working with EF CORE 2.1.1.
I created a function which accepts 3 parameters, inside that function I am executing a LINQ (lambda expression query), returning a list.
Here is my function :
public IEnumerable<Donneesource> GetAllSourcesFromBDD(DateTime PremierDateCom, DateTime DerniereDateCom, string Secteur) { try { //Récupération des données. IEnumerable<Donneesource> RawDatas = _sourceDAL.Donneesource .Where(ic => ic.EstCopieDestination == false) .Where(s => PremierDateCom != DateTime.MinValue && s.SComPremierDate.Value.Date == PremierDateCom.Date) .Where(s => DerniereDateCom != DateTime.MinValue && s.SComDerniereDate.Value.Date == DerniereDateCom.Date) .Where(s => Secteur != string.Empty && s.SSectNom == Secteur) .ToList(); return RawDatas; } catch(Exception) { return null; } } By default I set DateTime params to DateTime.MinValue (PremierDateCom,DerniereDateCom) and string param to string.Empty (Secteur).
I am trying to create a single query with where clauses. I want to ignore the where clauses with default params. For example If PremierDateCom = DateTime.MinValue (or other params) then I want to ignore the where clauses if something I want to include my where clause in my query.
I don't want to create a query like this:
//Filtre if (PremierDateCom != DateTime.MinValue) RawDatas = RawDatas.Where(x => x.SComPremierDate.Value.ToShortDateString() == PremierDateCom.ToShortDateString()); //Filtre if (DerniereDateCom != DateTime.MinValue) RawDatas = RawDatas.Where(x => x.SComDerniereDate.Value.ToShortDateString() == DerniereDateCom.ToShortDateString()); //Filtre if (Secteur != null) RawDatas = RawDatas.Where(x => x.SSectNom == Secteur);
IQueryableand how it works. Assuming_sourceDAL.Donneesourcereturns anIQueryable, then it will not be inefficient.