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.

有帮助吗?

解决方案

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()));

其他提示

If you are not familiar with Lamba, start learning simple LinQ, before you move on to lambda inside Linq queries.

You code shoud be like this:

public bool existsInDBAndHasCategories(string path)
{
    using (WinFileContextContainer c = new WinFileContextContainer())
    {
        var query = from f in c.File
            where f.Path == path &&
            (f.Categories != null || f.Categories.Count != 0)
            select f;
        return (f.Count != 0)
    }
}    
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top