Search code examples
c#entity-frameworkdatabase-performance

Reduce database calls with Entity Framework


Would it be possible to write this in 1 statement (make only 1 db call?) and still be able to differentiate between "The member did not exist" and "The member did exist but had no dogs".

public IEnumerable<Dog> GetDogsOfMember(int id)
{
    if (dbContext.Members.Any(i => i.ID == id))
    {
        return dbContext.Dogs.Where(i => i.Member.ID == id);
    }

    return null;
}

Solution

  • If each Dog already contains a reference to the Member, you can expose the other end of the relationship (if you didn't already):

    public class Member
    {
        public int ID { get; set; }
        // ...
        public virtual ICollection<Dog> Dogs { get; set; }
    }
    

    Then you can issue a single efficient query using Include():

    public IEnumerable<Dog> GetDogsOfMember(int id)
    {
        var memberWithDogs = dbContext.Members
                                      .Include(i => i.Dogs)
                                      .SingleOrDefault(i => i.ID == id);
    
        if (memberWithDogs != null)
            return memberWithDogs.Dogs;
    
        return null;
    }