Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 651
Pierre Avatar asked Feb 03 '26 17:02

Pierre


1 Answers

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;
}
like image 155
haim770 Avatar answered Feb 05 '26 08:02

haim770



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!