Search code examples
c#entity-frameworkwhere-clausenavigation-properties

How to search the property of a Navigation property


I'm creating a database using ASP.NET which features two classes, Countries and Species. The Species model contains an ICollection of type Country, and I am trying to allow for a search string on the Species Index view to check not only for names of Species, but if the user types the name of a Country instead, to return Species who's Country Collections include a Country with a Name that matches the search string:

public ActionResult Index(string searchString, string Poison, string Venom)
{
    var species = db.Species.Include(s => s.Countries);
    if (!String.IsNullOrEmpty(searchString))        
    {   
        species = species.Where(s => s.Name.Contains(searchString) || **s has a country who's Name contains searchString**);    
    }
}

This is my first question on stackoverflow, I'm not sure how many examples of my failed attempts are required, but the error messages I have received are largely based on being unable to convert type Country to String:

Values of type 'collection[NSDBz.DAL.Country(Nullable=True,DefaultValue=)]' can not be converted to string.

I can see there are similar questions being asked but their requirements are a bit more intricate so I'm unable, at my present skill level, to apply the solutions there to my problem here.


Solution

  • Based on your error, it appears you are trying to compare the Countries collection to the string, rather than checking if any of the countries in the collection have a matching name. I would suggest trying something similar to the following:

    s.Countries.Any(c => c.Name.Contains(searchString))