Michel
Michel

Reputation: 23615

Conditional Where statement in Linq

My Linq statement gives an error. Now the issue is that I'm at a project that uses a custom built datalayer, so I don't know wether I'm creating the wrong Linq statement or that the datalayer just can't handle it.

So here's the statement:

IQueryable<Affiliate> temp;

Func<RolePersonRole, bool> func;
if (roleMustBePrimary)
{
    func  = role => role.RolePersonRoleIsPrimary.Value == true;    
}
else
{
    func = role => role.RoleId == role.RoleId;

}
temp = (from affiliate in DataFacade.Instance().Tables(SessionTicket).Affiliates()
        join role in DataFacade.Instance().Tables(SessionTicket).RolePersonRoles().Where(func) on affiliate.PersonId
            equals role.PersonId
        where role.RoleId == roleId
                && affiliate.AffiliateAssuranceLevel == assuranceLevelEnum
        select affiliate);

The meaning is that if the bool roleMustBePrimary is true, a where statement should be added, and if it's false, it should not be added (hence the role => role.RoleId == role.RoleId).

The error I'm getting is:

The expression of type 'System.Collections.Generic.IEnumerable`1[SkillsNG.Modules.RolePersons.Entities.RolePersonRole]' is not a sequence

Upvotes: 0

Views: 191

Answers (1)

Wasp
Wasp

Reputation: 3425

As Wouter said, you do not need the .Where(), you can express it more clearly:

var temp = 
    from affiliate in DataFacade.Instance().Tables(SessionTicket).Affiliates()
    join role in 
        from r in DataFacade.Instance().Tables(SessionTicket).RolePersonRoles()
        where roleMustBePrimary && r.RolePersonRoleIsPrimary.Value 
              || !roleMustBePrimary
        select r
    on affiliate.PersonId equals role.PersonId
    where role.RoleId == roleId
          && affiliate.AffiliateAssuranceLevel == assuranceLevelEnum
    select affiliate;

Upvotes: 2

Related Questions