加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#方法可以允许可空列表作为参数吗?

发布时间:2020-12-15 23:31:39 所属栏目:百科 来源:网络整理
导读:我正在尝试编写一个允许搜索ID列表的方法,但我想允许列表是可选的.我见过List string的例子但我在使用List Guid时遇到了麻烦. 在LinqPad中尝试这个方法,我收到消息: Unable to create a null constant value of type ‘System.Collections.Generic.List`1[[
我正在尝试编写一个允许搜索ID列表的方法,但我想允许列表是可选的.我见过List< string>的例子但我在使用List< Guid>时遇到了麻烦.

在LinqPad中尝试这个方法,我收到消息:

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.

这是方法:

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();
}

更新:感谢您的评论,这就是我的所作所为:

public static ICollection<Project> GetProjectsAllowed
(
    this IMkpContext db,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();
}

解决方法

C#方法可以接受空列表.您遇到的问题是LINQ查询本身.

您不能将profOrgIds列表上的NULL检查传递到与实体框架相关的LINQ查询,因为实体框架LINQ提供程序(在此处使用,因为您正在对EF数据库上下文对象执行LINQ查询)无法转换查询语法到等效的T-SQL.

换句话说,摆脱

profOrgIds == null

从查询中你应该没问题,但是在调用查询之前你需要检查profOrgIds是否为null.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读