entity-frameworklinqdbcontextdbset

DbSet LINQ query to inner collection does not throw an Argumentexception


I met this for me kind of strange behavior and wonder what is behind that it works how it works.

_dbContext.MyDbSet.Where(setItem =>
    setItem.InnerCollection.All(...)
).ToList()

This piece of code works fine even if the InnerCollection is null. Surprise for me is, that both these pieces throw ArgumentNullException on the inner collection.

_dbContext.MyDbSet.Local.Where(setItem =>
    setItem.InnerCollection.All(...)
).ToList()

_dbContext.MyDbSet.ToList().Where(setItem =>
    setItem.InnerCollection.All(...)
).ToList()

Can anybody explain me how is this possible? Is there any null constrol behind the DbSet? Thanks in advance.


Solution

  • The answer to your first question is very simple:

    when using

    _dbContext.MyDbSet.Where(setItem =>
        setItem.InnerCollection.All(...)
    ).ToList()
    

    EF generates a JOIN statement and filtering is performed on the database and therfore no ArgumentNullException is raised.

    While when calling Local or ToList() before filtering all your entities are loaded from the database and get filtered in-memory. Therefore in this versions the lists are null if you do not include the corresponding navigation properties and an ArgumentNullException occurres.