Skip to content

Instantly share code, notes, and snippets.

@MirzaLeka
Created July 16, 2023 19:02
Show Gist options
  • Save MirzaLeka/edf8035634a4fe213978819ffdb7cf17 to your computer and use it in GitHub Desktop.
Save MirzaLeka/edf8035634a4fe213978819ffdb7cf17 to your computer and use it in GitHub Desktop.
EF Core LINQ Hacks

EF Core Query All Paramaters that are not null

If you find yourself in a situation where you have multiple parameters where you can query:

  • by one param
  • combination of params
  • all params

And you want to execute just one DB call and avoid querying with params that are NULL, do the following:

string ID;
string firstName;
string lastName;

var query = dbContext.Table.AsQueryable();

query = 
  query.Where(u => 
    (string.IsNullOrEmpty(userID) || u.ID == ID)
    && (string.IsNullOrEmpty(firstName) || u.FirstName == firstName)
    && (string.IsNullOrEmpty(lastName) || u.LastName == lastName))
  .List();  
   
  • If String is null or empty, than the first part of the criteria will be false, thus EF will ignore the line.
  • If string is neither null nor empty, then the criteria on the right will be questioned

To improve the conditions with case-insensitive search criteria you can make use of string.Equals():

  string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);

And apply:

var ignoreCasing = StringComparison.CurrentCultureIgnoreCase;

query = 
  query.Where(u => 
    (string.IsNullOrEmpty(userID) || string.Equals(u.ID, ID, ignoreCasing))
    && (string.IsNullOrEmpty(firstName) || string.Equals(u.FirstName, firstName, ignoreCasing))
    && (string.IsNullOrEmpty(lastName) || string.Equals(u.LastName, lastName, ignoreCasing)))
  .List();  
   
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment