user706058
user706058

Reputation: 415

Linq to Entities: can't get collection query to work

I'm struggling to get a collection of records using L2E. Here's the model view: http://pascalc.nougen.com/stuffs/aspnet_linq_model2.png

I have a user identifier, which is associated to 1 or many UserGroup which themselves are linked to TestCase. I would like to get all TestCases of all groups the user id X is associated to.

I also notice that I don't get all Project for users that are associated to 2 (or more).

Here's how I do so far:

    QASModel.QASEntities qasEntities = new QASModel.QASEntities();
QASModel.User authenticatedUserEntity = (from u in qasEntities.Users
                                         where u.ID.Equals(authenticatedUserId)
                                         select u).FirstOrDefault();
// Get the authenticated user usergroups
var usergroup = authenticatedUserEntity.UserGroups.FirstOrDefault();
// Get all testcases of all user group the authenticated user is associated to
var allTestcases = usergroup.TestCases;
// Get the authenticated user projects based on it's usergroup(s)
var authenticatedUserProjects = usergroup.Projects;

authenticatedUserProjects give back only 1 project, where the user is linked to 2 projects. And allTestcases gives back no result, although there are about 8 entries in TestCases associated to a project associated to one of the same UserGroup the user belongs to.

Thanks

Upvotes: 1

Views: 212

Answers (2)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102408

I think your problem is in this line:

var usergroup = authenticatedUserEntity.UserGroups.FirstOrDefault();

Shouldn't your code get all UserGroups of that User? The above line will return only 1 UserGroup, this is, if the user belongs to more than 1 UserGroup the 2nd one won't be returned.

To correct this:

var userTestCases = new List<TestCase>();
var userProjects =  new List<Project>();

foreach(UserGroup ug in authenticatedUserEntity.UserGroups)
{
    userTestCases = userTestCases.Concat(ug.TestCases);

    // Get the authenticated user projects based on it's usergroup(s)
    userProjects = userProjects.Concat(ug.Projects);

    ...
}

Upvotes: 1

AD.Net
AD.Net

Reputation: 13399

var usergroup = authenticatedUserEntity.UserGroups.FirstOrDefault();

probably is wrong, since you want all usergroups the user is associated with. In any case you can easily revert the query to work like this

var testcases = from tc in new QASModel.QASEntities().TestCases
where tc.UserGroup.UserId == USERID
select tc

This way you won't have to execute multiple queries to get all test cases, each FirstOrDefault or ToList or ForEach will actually execute the query.

Upvotes: 0

Related Questions