c# - 使用 EF Core 2.1 从输入列表中获取数据库中不存在的项目

标签 c# linq entity-framework-core

我想从输入列表中获取数据库表中不存在的项目。

我传递了一个ID列表,然后我想返回那些在我的表中不存在的ID

这是我目前拥有的:

var input = new List<string>() // list of Ids, for example count of 10

var itemsThatExistInDb = await DbContext.Set<Data>() // in table exist 100k+ records,
        .AsQueryable()                               // can't use simple !Contains()
        .Where(x => input.Contains(x.Id))
        .Select(x => x.Id)
        .ToListAsync();

var itemsThatNotExistInDb = input.Except(itemsThatExistInDb).ToList();

如何在不使用 Except() 等 linq 扩展的情况下,在 EF Core 2.1 中编写查询以从我的输入列表中获取数据库中不存在的项目?如果可能的话,我想将那些 Ids 从我的数据库查询中直接获取到 DbContext

最佳答案

如果你不想使用!contain,你可以使用如下逻辑方法:

datatTable 是您的表的内容。

List<string> fullList = new List<string>() { "3", "1", "2" }; //or any dynamic list content or class list based on requirement.
List<string> itemsThatNotExistInDb = new List<string>(); //New container list same as fullList
            foreach (var item in fullList)
            {
                var isRemoved = dataTable.RemoveAll(a => a.Id == item) == 1 ? true : false;
                if (isRemoved)
                {
                    itemsThatNotExistInDb.Add(item);
                }
            }

关于c# - 使用 EF Core 2.1 从输入列表中获取数据库中不存在的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61629038/

相关文章:

c# - EntityFramework Core 6 升级无法加载类型 IAsyncQueryProvider

C# 增加控制台日志大小

c# - 使用表达式、静态方法和基对象获取类的属性名称

c# - 在 List<T>.ForEach ForEach 方法中更改元素值

asp.net-core - 删除 EF Core 中的相关数据

entity-framework-core - 如何在内存中没有 key 的情况下对 EF core 3 View 进行单元测试?

c# - 非只读类已经存在时的只读类设计

c# - 使用 "variable !== FALSE"的缺点

c# - 升级到 5.0.0 后 TokenValidationParameters 不再起作用

c# - 如何从列表中快速删除项目