4

I have a linq to sql database. Very simplified we have 3 tables, Projects and Users. There is a joining table called User_Projects which joins them together.

I already have a working method of getting IEnumberable<Project> for a given user.

from up in User_Projects
select up.Project;

Now I want to get the projects the user isn't involved with. I figured the except method of IEnumerable would be pretty good here:

return db.Projects.Except(GetProjects());

That compiles, however I get a runtime error: "Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator."

Is there any way to get around this?


Update:

A few views but no answers :p

I have tried this:

        IEnumerable<Project> allProjects = db.Projects;
        IEnumerable<Project> userProjects = GetProjects();
        return allProjects.Except(GetProjects());

I know it's essentially the same as the original statement - but now i dont get a runtime error. Unfortunately, it doesn't really do the except part and just returns all the projects, for some reason

Chris James
  • 11,571
  • 11
  • 61
  • 89

3 Answers3

6

Linq to Sql doesn't understand how to work with an arbitrary in-memory sequence of objects. You need to express this in relational terms, which works on IDs:

var userProjectIds =
    from project in GetProjects()
    select project.ProjectId;

var nonUserProjects =
    from project in db.Projects
    where !userProjectIds.Contains(project.ProjectId)
    select project;
Bryan Watts
  • 44,911
  • 16
  • 83
  • 88
3

You could try something simple like

User u = SomeUser;

from up in User_Projects
where up.User != u
select up.Project;
Agies
  • 1,105
  • 8
  • 12
0

try this:

var userProjects = GetProjects();
return db.Projects.Except(userProjects.ToArray());

The ToArray should force evaluation of the sequence (if I'm understanding the issue right) and allow the operation to succeed.

technophile
  • 3,556
  • 1
  • 20
  • 24