NHead
NHead

Reputation: 129

EntityFramework group by linq query

I have the following 2 tables:

Account
----------
account_id **PK**
account_name
account_type_id **FK** 

Account_Type
-------------
account_type_id **PK (FK in account table)**
account_type_name
account_type_reference

Using entity framework I am trying to get the results like this:

DbSet.Where(Account => Account.Account_Type.account_type_name == 'type1').ToList());

This works however I am not sure how to add group by to this statement. I want to group these by Account_Type_id, Account_type_name, Account_type_reference so I don't get duplicate rows. How can I do that?

Thanks

Upvotes: 2

Views: 730

Answers (1)

John
John

Reputation: 3702

You can add grouping with the Linq GroupBy function:

DbSet.Where(Account => Account.Account_Type.account_type_name == "type1")
    .GroupBy(x => x.Account_Type.account_type_id).ToList();

Then you end up with a list of groups. Each group then has the Key (account_type_id) and the group itself is an IEnumerable of Account objects

Upvotes: 1

Related Questions