user523098
user523098

Reputation:

Entity Framework subquery

Guys I am new to Entity Framework and I'm having a bt of a problem that I have been trying to solve for quite a while. Basically I have 4 entities: users, groups, books and readingLists. A user can join a group and a group contains books - defined by readingList. I am trying to display a list of books for a specific group, the SQL looks like this:

SELECT * FROM Books b
WHERE b.Id IN (
    SELECT BookID FROM ReadingList rl
        WHERE rl.GroupID = '3')

I determine the GroupID being searched by querying the current user from a UserRepository and currently the 'get books by group' method is looking like this:

// Get books by group
public IQueryable<Book> GetGroupBooks(string username)
{
    UserRepository userRepository = new UserRepository();
    int groupId = userRepository.GetUserGroupId(username);

    IQueryable<Book> q = from b in entities.Books 
                         where b.Id == 7 // temp - these values should be determined by 
                                         // rl in entites.ReadingList select rl.BookID where r.GroupID == groupID
                         select b;

    return q;
}

Obviously this is a temporary measure and only returns one book, but I have included it for reference. Any help or advice here would be much appreciated.

Thanks

Upvotes: 10

Views: 14508

Answers (2)

Nix
Nix

Reputation: 58522

Personally I think there is a better solution(untested of course):

First select from ReadList by GroupdID, then join in books on BookID.

IQueryable<Book> q = 
       from rl in entities.ReadingList
       join b in entities.Books on rl.BookID equals b.BookID
       where rl.GroupdID ==groupID
       select b;

var books = q.ToList()

Please let me know if you have any issues.

Upvotes: 6

Mayank
Mayank

Reputation: 1631

I haven't tested it but hopefully it will work.

entities.Books.Where(
b => entities.ReadingList.
Where(rl => rl.GroupId == groupId).
Select(rl => rl.BookId).
Contains(b.BookId)
)

Upvotes: 5

Related Questions