请参见下面的代码:
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);
}
}
我试图有条件地添加那些Where方法,例如:
albumList = context.Albums
if (someCondition)
{
.Where(a => a.ReleaseYear.Equals(year));
}
if (someOtherCondition)
{
.Where(a => a.Composer.Equals(composer));
}
.ToList<AlbumEntity>();
但是,我收到“当前上下文中不存在此位置”的编译器错误。
我该如何实现?谢谢。
答案 0 :(得分:2)
您可以将它作为一个巨大的表达来实现,但这很难维护。
尝试在变量中建立查询,然后最后执行它。
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();