LINQ: adding where clause only when a value is not null

后端 未结 10 939
花落未央
花落未央 2020-12-15 17:38

I know a typical way is like this:

IQueryable query = from staff in dataContext.Staffs;
if(name1 != null)
{
     query = from staff in query where (staff.nam         


        
10条回答
  •  离开以前
    2020-12-15 18:01

    I've seen this pattern in standard SQL, and it seems useful if you have several parameters that may be NULL. For example:

    SELECT * FROM People WHERE ( @FirstName IS NULL OR FirstName = @FirstName )
                           AND ( @LastName IS NULL OR LastName = @LastName )
    

    If you see this in LINQ, it's possible they just blindly translated their old SQL-queries.

提交回复
热议问题