Search code examples
asp.netlinq-to-entitiesentitycollection

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


Solution

  • 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);
    
        ...
    }