Use linq to count in many to many table

I have two table with many-to-many relation ship: director(id, name), movie(id, name, year) and the relation ship table is dir_mov(did,mid) I want to use and group by the number of movie a director direct using linq. How can i solve this?

Upvotes: 0

Views: 111

Answers (1)

is_oz
is_oz

Reputation: 993

You can use join and group by. Joining director table and relationship table is enough.

var result = yourDbContext.director
                .Join(yourDbContext.Dir_Mov, d => d.Id, m => m.did,
                    (d, m) => new {DirectorId = d.Id, MovieId = m.mid})
.GroupBy(g => g.DirectorId)
.Select(s => new {s.Key, CountOfMovie = s.Count()}).ToList();

You have to change yourDbContext is your own context or repository.

Upvotes: 1

Related Questions