Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a C# method allow nullable lists as parameters?

Tags:

c#

linq

I'm trying to write a method that allows for a list of Ids to search for, but I would like to allow the list to be optional. I've seen examples of List<string> but I'm having trouble with List<Guid>.

Trying this method in LinqPad, I get the message:

Unable to create a null constant value of type 'System.Collections.Generic.List`1[[System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only entity types, enumeration types or primitive types are supported in this context.

Here's the method:

public static ICollection<Project> GetProjectsAllowed
(
    this IMkpContext db,
    Guid profileId,
    List<Guid> profOrgIds = null
)
{
    var projects = (from p in db.Project.Include(p => p.Proposals)
                    join po in db.ProfileOrganization on p.CreatedById equals po.ProfileId
                    where (profOrgIds == null || profOrgIds.Contains(po.OrganizationId))
                        && p.IsActive && po.IsActive
                    select p);

    return projects.ToList();
}

UPDATE: Thanks to your comments, here's what I did:

public static ICollection<Project> GetProjectsAllowed
(
    this IMkpContext db,
    Guid profileId,
    List<Guid> profOrgIds = null,
    List<Guid> projectIds = null
)
{
    var projects = (from p in db.Project.Include(p => p.Proposals)
                    where p.IsActive
                    select p);

    if (profOrgIds != null && profOrgIds.Any())
    {
        var profileIds = db.ProfileOrganization
            .Where(po => po.IsActive && profOrgIds.Contains(po.OrganizationId))
            .Select(po => po.ProfileId);
        projects = projects.Where(p => profileIds.Contains(p.CreatedById));
    }

    if (projectIds != null && projectIds.Any())
        projects = projects.Where(proj => projectIds.Contains(proj.ProjectId));

    return projects.ToList();
}
like image 508
M Kenyon II Avatar asked Mar 13 '23 23:03

M Kenyon II


1 Answers

A C# method can accept null lists. The problem you have is with the LINQ query itself.

You cannot pass a NULL check on the profOrgIds list into an Entity Framework related LINQ query, since the Entity Framework LINQ provider (which is in use here, as you are executing LINQ queries against an EF database context object) has no way to translate the query syntax into equivalent T-SQL.

In other words, get rid of

profOrgIds == null

from the query and you should be fine, but you will need to check profOrgIds is null before you call the query.

like image 172
Jason Evans Avatar answered Mar 24 '23 09:03

Jason Evans