Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many to many ordered by count of relationship (Entity Framework, Linq)

i have a table structure like this...

alt text

When I import this into entity framework it looks like this...

alt text

What I need to do is build a query from LINQ that will return a list of every unique store, populated with a list of people who like that store. (easy, right?)

THE CATCH: I need to filter the list to the person's list of friends that get passed in as a List to the linq query (comes from facebook, so relationships are not in db)...

ONE MORE THING: i need to return if the store is a favorite of the person requesting the data (the uid as shown below)

OK, ANOTHER THING: I need to return the list sorted by the highest number of friends who like an item to lowest (the ui below is wrong in that regard)

Here is the method signature of the linq query i need

public List<Store> GetTopStoresFilteredByFriends
          (int uid, List<int> friends, int size = 10){

}

To return a user interface that looks like this...

alt text

like image 916
Rod Johnson Avatar asked Oct 11 '10 23:10

Rod Johnson


1 Answers

This query gives you a list of every unique store, populated with a list of people who like that store which is also liked by at least one of the friends in the list that you are passing order by the highest number of friends that like the store plus a flag to show whether or not each store is liked by the person who requested the data:

var query = (from s in ctx.Stores.Include("People")
             from p in s.People
             let n = friends.Sum(f => s.People.Count(item => item.PersonID == f))
             where friends.Any(f => f == p.PersonID)
             select new {
                 TheStore = s,
                 IsFavorite = s.People.Any(ppl => ppl.PersonID == uid),
                 N = n
             })
             .Distinct()
             .OrderByDescending(o => o.N);
like image 192
Morteza Manavi Avatar answered Oct 13 '22 11:10

Morteza Manavi