Search code examples
entity-frameworkentityexistsassociated-object

Entity Framework: check if object exists and check if it has an associated object


In a many-to-many relationship between File and Category I want to check if a file exists and if so, if it has any categories (because there's a chance it may not have any) :

        public bool existsInDBAndHasCategories(string path)
    {
        using (WinFileContextContainer c = new WinFileContextContainer())
        {
            return c.File.Any((o => o.path == path));
        }
    }    

This checks if a file with this path has a record in the database. I got this from a thread on this site. Truth be told I am still not good with LINQ and lambdas, so I don't know how to extend it to give me BOOLEAN for any categories as well. Thanks in advance for the time.


Solution

  • You just have to add another condition to your method (Assuming you have defined Categories as a list of Category in File class) :

    return c.File.Any((o => o.path == path && o.Categories.Any()));