【问题标题】:EF CORE PostgreSQL - Check if ALL elements of a List are contained in another ListEF CORE PostgreSQL - 检查列表的所有元素是否包含在另一个列表中
【发布时间】:2022-01-15 06:20:24
【问题描述】:

我正在寻找一种在实体框架中检查列表的所有元素是否包含在另一个列表中的方法。

我的应用程序是 .NET 6,我使用 Npgsql 查询我的 PostgreSQL 数据库,我有一个 ID 列表和一个与另一个表“Certifications”相关的类“Company”。

公司类如下所示:

    public class Company
    {
        public int ID { get; set; }
        public List<Certification> Certifications { get; set; }
        ...
    }

我的认证课程看起来像这样:

public class Certification
{
    public int ID { get; set; }
    public int? CompanyID { get; set; }
    public CertificationType Type { get; set; }

    public int CategoryID { get; set; }
    public virtual Category Category { get; set; }

    public int? RankingID { get; set; }
    public virtual Ranking Ranking { get; set; }
    ...
}

查询是显示公司的分页查询,它必须在数据库上执行(无客户端查询),我正在尝试使用 LINQ 编写它,但出现以下错误:

LINQ 表达式 'opt => DbSet() .Where(c0 => EF.Property(EntityShaperExpression: ALPHUBs.ML.Models.Company 值缓冲区表达式: ProjectionBindingExpression:EmptyProjectionMember IsNullable: 假 , "ID") != null && object.Equals( objA: (object)EF.Property(EntityShaperExpression: ALPHUBs.ML.Models.Company 值缓冲区表达式: ProjectionBindingExpression:EmptyProjectionMember IsNullable: 假 , “ID”), objB: (object)EF.Property(c0, "CompanyID"))) .Select(c0 => c0.CategoryID) .Any(p => p == opt)' 无法翻译。要么以可翻译的形式重写查询,要么切换到客户评估 通过插入对“AsEnumerable”、“AsAsyncEnumerable”的调用,显式地 “ToList”或“ToListAsync”。看 https://go.microsoft.com/fwlink/?linkid=2101038 了解更多信息。

我已经尝试过这些方式:

IQueryable<Company> query = this._context.Companies.AsNoTracking()
                                                    .Include(c => c.Certifications)
                                                    .AsSplitQuery();

List<int> categoryList = new List<int>() { 1, 3, 5 };

//ATTEMPT 1
query.Where(c => categoryList.All(opt => c.Certifications.Select(cert => cert.CategoryID).Contains(opt)));
//ATTEMPT 2
query.Where(c => categoryList.Except(c.Certifications.Select(cert => cert.CategoryID)).Count() == 0);

我可以让它工作的唯一方法是:

 c.Certifications.Any(cert => categoryList.Contains(cert.CategoryID));

但这给了我错误的结果,因为我需要拥有所有给定认证的所有公司,而不是至少拥有一个给定认证的公司。

【问题讨论】:

    标签: postgresql npgsql .net-6.0 c#-10.0 ef-core-6.0


    【解决方案1】:

    下面的内容怎么样:

    var categoryList = new List<int> { 1, 3, 5 };
    _ = ctx.Companies
        .Where(c => c.Certifications.Count(c => categoryList.Contains(c.ID)) == categoryList.Count)
        .ToList();
    

    这假设对于给定的公司,最多只有一个具有给定 ID 的认证。

    【讨论】:

    • 谢谢你为我节省了大量的调试时间:)
    猜你喜欢
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    相关资源
    最近更新 更多