Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

c# entity framework group by

// This works only in .NET 2.1 or lower
db.Clients.AsNoTracking()
 .Include(x => x.Purchases)
 .Where(x => x.Id == id)
 .GroupBy(x => x.PurchaseId)
 .ToList()
  
// For .NET 3.1 or higher you won`t be able to use GroupBy as in the query above
// Instead you have to convert your query to an enumerable
 db.Clients.AsNoTracking()
 .Include(x => x.Purchases)
 .Where(x => x.Id == id)
 .AsEnumerable() // Retrieves the data and groups them in C#
 .GroupBy(x => x.PurchaseId)
 .ToList()
  
// Or an other technique is to use SelectMany
 db.Clients.AsNoTracking()
 .Include(x => x.Purchases)
 .Where(x => x.Id == id)
 .Select(x => x.Purchases.Id)
 .SelectMany(key => db.Purchases
  .Where(y => y.Id == key))
 .ToList()
 
PREVIOUS NEXT
Tagged: #entity #framework #group
ADD COMMENT
Topic
Name
6+4 =