Skip to content
Advertisement

How many SQL Queries will be executed in the database through this EF

I have the following and want to know how many queries will be executed in the DB through this EF?

private static dbContext dbc = new ProfileDBC();

private static IQueryable<Profile> GetProfile()
{
  return dbc.Profiles;
}


private static IQueryable<Purchase> GetPurchases()
{
  return from a in dbc.Amount
            where a.IsPurchased
            select a;
}

static void Main (string[] args)
{
   var result = (from p in GetProfile()
                  join pa in GetPurchases()
                  on p.ID equals pa.ID
                  group p.total by pa into r
                  select new { r.name, totalpurchase = r.Sum( p=> p)});.ToList(); }
}

}

Advertisement

Answer

It will be one query, after you’ve solved the compiler error:

Sum( p=> p)});.ToList();

If you want to fetch items with their sub-items, like Schools with their Students, Customers with their Orders, or Profiles with their Purchases, consider a GroupJoin instead of a Join followed by a GroupBy. The nice thing is that you will also get the Profiles that have no Purchases:

var profilesWithTheirPurchases = dbContext.Profiles.GroupJoin(dbContext.Purchases,

    // parameter KeySelector: compare primary and foreign key:
    profile => profile.Id,           // from every Profile take the Id
    purchase => purchase.ProfileId,  // from every Purchase take the ProfileId

    // parameter resultSelector: take every Profile with its zero or more Purchases
    // to make one new
    (profile, purchasesOfThisProfile) => new
    {
         Name = profile.Name,
         TotalPurchases = purchasesOfThisId.Select(purchase => purchase.Amount)
                                           .Sum(),
    });
         
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement