tags:

views:

54

answers:

2

The scenario is I want to get the users who has less than 2 photos.

There are two table:

[Users] (UserId, UserName) 

[UserPhotos] (PhotoId, PhotoName, UserId) 

UserId is a Foreign Key but I do not want to use association like user.Photos.

A user may have none photo in the [UserPhotos] table.

How to use Linq To Sql to get List<User> who has less than 2 photos?

+1  A: 

What's wrong with this??

var query = from u in dbContext.Users
            where u.Photos.Count > 2
            select u;

That would be the easiest by far - why do you want to specifically not use this method??

marc_s
Because there is no FK in the old-app, and I can not add a FK.
Mike108
You could lazy-load the photos that are associated with the user inside the Users Model. This will allow the above functionality...
Alexander
+3  A: 

Maybe this: (fixed version)

List<User> users = UserPhotos.GroupBy(i => i.UserId)
                .Where(i => i.Count() > 2).Distinct()
                .Join(Users, o => o.Key, i => i.UserId, (o, i) => i)
                .ToList();

solution for changed question:

    List<User> result = Users.Where(user => !UserPhotos.GroupBy(i => i.UserId)
            .Where(i => i.Count() >= 2).Distinct()
            .Any(i => i.Key == user.UserId)).ToList();
Nagg
Thank you very much.
Mike108
Oh, there is a bug: the result missed the users who has none photo.I edited the question, get the users who has less than 2 photos.
Mike108
ok, try this one.
Nagg
Yes. It works. Thank you.
Mike108