-1

Please see code below:

using (var context = new MusicCatelogContext())
        {
            try
            {                    

                albumList = context.Albums                        
                    .Where(a => a.ReleaseYear.Equals(year))
                    .Where(a => a.Composer.Equals(composer))
                    .ToList<AlbumEntity>();

            }
            catch (Exception e)
            {
                Trace.WriteLine(e.Message);
                Trace.WriteLine(e.InnerException);
            }
        }

I am trying to add those Where methods conditionally, so something like:

                    albumList = context.Albums                 

                    if (someCondition)
                {
                    .Where(a => a.ReleaseYear.Equals(year));
                }


                    if (someOtherCondition)
                {
                    .Where(a => a.Composer.Equals(composer));
                }                                             

                    .ToList<AlbumEntity>();

However, I get a "Where does not exist in the current context" compiler error.

How can I achieve this? Thanks.

John Steed
  • 599
  • 1
  • 12
  • 31

1 Answers1

2

You could do it as one huge expression, but that becomes hard to maintain.

Try building up the query in a variable, then execute it at the end.

  IQueryable<AlbumEntity> query = context.Albums;

  if (someCondition)
  {
      query = query.Where(a => a.ReleaseYear.Equals(year));
  }

  if (someOtherCondition)
  {
      query = query.Where(a => a.Composer.Equals(composer));
  }    

  albumList = query.ToList();
  • That is exactly what I was looking for and worked perfectly. It seems IQueryable was the key. Thanks very much. – John Steed Jul 09 '18 at 10:33