I’m trying to convert an SQL query to Linq and I get an exception:
System.NotSupportedException : Queries with local collections are not supported.
So is there a way to rephrase the query in a ‘legal’ way?
Thanks for any suggestions,
Anders, Denmark
PS: I’ve seen the ‘solution’ to call .ToList() on any query before calling .Contains() — but that would just result in four separate queries, right?
At the bottom is my code that fails on execution.
The logical problem I’m trying to solve is to find the ‘structures’ that a user have access to, either by direct access or by membership of a group that has access. We do not have nested groups.
In other words, the user should have access if any of the following is true:
- The user created the structure (id is ‘stamped into’ the structure record).
- An entry exists in the PermissionUsers table, linking the Permissions Table with the users table.
- an entry exists in the PermissionGroups table, linking the Permissions table with the Groups table and the user is referenced in
the UsersGroups table, linking Users table with the Users table.
Applying permissions/restricting result to accessible items is a relatively new thing and we would like the database to do the heavy pulling ;).
[TestFixture]
public class LinqTest : CommandBasedIntegrationTestBase
{
[Test, Category("SuperIntegration"), RequiresSTAAttribute]
public void TestThat()
{
DbIntegrationTestHelper.SetState();
var dataContextProvider = ObjectFactory.GetInstance<IDataContextProvider>();
const int userId = 1;
var environment = ObjectFactory.GetInstance<IState>().DatabaseEnvironment;
var dataClasses1DataContext = dataContextProvider.GetContext(environment);
var idsByCreator = from r in dataClasses1DataContext.Structures where r.CreatedUserId == userId select r.StructureId;
var idsByUserAccess = from r in dataClasses1DataContext.PermissionUsers where r.UserId == userId select r.StructureId;
var idsOfGroupsContainingUser = from r in dataClasses1DataContext.UsersGroups where r.UserId == userId select r.GroupId;
var idsByGroupAccess = from r in dataClasses1DataContext.PermissionGroups where idsOfGroupsContainingUser.Contains( r.GroupId ) select r.StructureId;
var res = from s in dataClasses1DataContext.Structures
where
idsByCreator.Contains(s.StructureId) ||
idsByUserAccess.Contains(s.StructureId) ||
idsByGroupAccess.Contains(s.StructureId)
select s;
foreach (var structure in res)
{
Debug.WriteLine(structure.Name);
}
}
}
Give a try to
JOINs,UNIONsExample
Update
I have removed unnecessary call to
Distinct()according to @Magnus comment. Call toDistinct()would be necessary only ifConcat()instead ofUnion()is used.