Trouble writing predicates to search a repository with Entity Framework (equivalent to using a Join in SQL)

We are using code first Entity Framework 4.1 to persist data. Some of our entities have a relationship like this:

[Serializable]
public class Conference
{
    private IList<Attendee> people;
    private string name;        

    public IList<Attendee> People
    {
        get { return this.team; }
        private set { this.team = value; }
    }

    public string Name
    {
        get { return this.name; }
        private set { this.name = value; }
    }
}

[Serializable]
public class Attendee
{
    private string firstname;
    private string surname;

    public string Firstname
    {
        get { return this.firstname; }
        private set { this.firstname = value; }
    }

    public string Surname
    {
        get { return this.surname; }
        private set { this.surname = value; }
    }
}

I would like to query our repository of conferences using LINQ. I can find a conference easily by name using a search specification like this:

public class ConferenceNameSearch : ISpecification<Conference>
{
    public Expression<Func<Conference, bool>> IsSatisfied()
    {
        return a => a.Name == "Christmas Party";
    }
}

But I am having real trouble writing a search specification that would return all conferences attended by at least 1 person who has the first name "David":

public class ConferenceAttendeeNameSearch : ISpecification<Conference>
{
    public Expression<Func<Conference, bool>> IsSatisfied()
    {
        return a => a.People.Contains( ???? err "David";
    }
}

Is there a way to do this? Also, taking it up 1 more level of complexity, if instead of just searching for conferences with an attendee called "David" I had a List<string> names that I wanted to match, would this be possible too?

Thanks for your help!

Answers


It looks like you want IEnumerable<T>.Any:

public class ConferenceAttendeeNameSearch : ISpecification<Conference>
{
    public Expression<Func<Conference, bool>> IsSatisfied()
    {
        return a => a.People.Any(p => p.FirstName.Equals("David"));
    }
}

Any returns a bool indicating whether any of the sequence's elements matched the condition. You might describe its behavior as similar to sequence.Where(condition).Count() > 0.

A related method you should know about (though it doesn't apply here) is IEnumerable<T>.All.


Need Your Help

IE7 having problems when redirected to large excel files

asp.net internet-explorer download

We've got a page in our asp.net web system that uses response.redirect to redirect the user directly to an excel file so it will download "automatically" without the user having to to a right click /

HTTP: Missing resource string

http localhost xpages

I am trying to open my xPages application on local host but I receive this error: