Reducing database queries with Entity Framework
Is it possible to write this down in 1 expression (make only 1 db call?) And still be able to distinguish between "Member did not exist" and "Member existed but did not have 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;
}
+3
source to share
1 answer
If each Dog
already contains a link to Member
, you can open the other end of the relationship (if you haven't already):
public class Member
{
public int ID { get; set; }
// ...
public virtual ICollection<Dog> Dogs { get; set; }
}
Then you can create one 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;
}
+5
source to share