0

I'm currently using a lambda to set a property.

Team = department.Teams
                 .Where( t => t.GUID == a.Personnel.Roles
                        .Where(r=>r.Department==department && r.EndDate==null)
                        .SingleOrDefault()
                        .DeptTeamGUID)
                 .FirstOrDefault().Name

Department has a bunch of teams. A personnel has a role that is connected to that team. The PersonnelRole contains data about the department and which team the role is a part of.

However sometimes a personnel can have a role with no team. In this case I get a "Object reference not set to an instance of an object." exception.

I have also tried to modify the lambda to filter out Roles that doesn't have a DeptTeamGUID, but my logic seems off.

Team = department.Teams
                 .Where( t => t.GUID==a.Personnel.Roles
                         .Where( r => r.Department==department && r.EndDate==null 
                                      && r.DeptTeamGUID !=null)
                         .SingleOrDefault().DeptTeamGUID)
                 .FirstOrDefault().Name

Can anyone guide me in the right direction?

1 Answer 1

3

You are getting the null-reference exception because you are trying to read a property from a null-reference, when you are doing it using the construct .SingleOrDefault().PropertyName.

You have to change .SingleOrDefault().PropertyName to .Select(x => x.PropertyName).SingleOrDefault(), like this:

Team = department.Teams
    .Where(t => t.GUID == a.Personnel.Roles
        .Where(r => r.Department == department && r.EndDate == null)
        .Select(x => x.DeptTeamGUID)
        .SingleOrDefault()
    )
    .Select(x => x.Name)
    .FirstOrDefault();

Note: this should make it work, but since t.Guid == null is not true, your case of personnel with no team will not be returned by the query.

Another note: I suspect that you might miss some results that you would normally expect, since you are using the .SingleOrDefault() in your subquery. Perhaps you should use .Contains(...) to check all guid's. Like this:

Team = department.Teams
    .Where(t => a.Personnel.Roles
        .Where(r => r.Department == department && r.EndDate == null)
        .Select(x => x.DeptTeamGUID)
        .Contains(t.GUID)
    )
    .Select(x => x.Name)
    .FirstOrDefault();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.