首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Ids列表中获取缺少的ids

从Ids列表中获取缺少的ids
EN

Stack Overflow用户
提问于 2022-07-18 16:29:24
回答 1查看 157关注 0票数 1

我试图从实体框架核心中的另一个in列表中检索数据库中缺少的in列表。

有办法把这个电话接到一条条线吗?

代码语言:javascript
复制
public static async Task<IEnumerable<TKey>> GetMissingIds<T, TKey>(
        this IQueryable<T> db, IEnumerable<TKey> ids)
    where T : BaseEntity<TKey>
    {
        var existingIds = await db
            .AsNoTracking()
            .Where(entity => ids.Contains(entity.Id))
            .Select(entity => entity.Id)
            .ToListAsync();
    
        return ids.Except(existingIds);
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-19 15:03:42

EF只支持本地集合(除了小例外)的Contains,因此没有有效的方法通过LINQ查询检索数据库中不存在的in。

无论如何,还有第三方扩展可以实现linq2db.EntityFrameworkCore (请注意,我是创建者之一)。

使用此扩展,您可以将本地集合连接到LINQ查询:

代码语言:javascript
复制
public static Task<IEnumerable<TKey>> GetMissingIds<T, TKey>(
    this IQueryable<T> query, IEnumerable<TKey> ids, CabcellationToken cancellationToken = default)
 where T : BaseEntity<TKey>
{
    // we need context to retrieve options and mapping information from EF Core
    var context = LinqToDBForEFTools.GetCurrentContext(query) ?? throw new InvalidOperationException();

    // create linq2db connection
    using var db = context.CreateLinqToDbConnection();

    var resultQuery =
        from id in ids.AsQueryable(db) // transform Ids to queryable
        join e in query on id equals e.Id into gj
        from e in gj.DefaultIfEmpty()
        where e == null
        select id;

    // there can be collision with EF Core async extensions, so use ToListAsyncLinqToDB
    return resultQuery.ToListAsyncLinqToDB(cancellationToken);
}

这是生成的查询的示例:

代码语言:javascript
复制
SELECT
    [id].[item]
FROM
    (VALUES
        (10248), (10249), (10250), (10251), (10252), (10253), (10254),
        (10255), (10256), (10257), (10023)
    ) [id]([item])
        LEFT JOIN (
            SELECT
                [e].[OrderID] as [e]
            FROM
                [Orders] [e]
        ) [t1] ON [id].[item] = [t1].[e]
WHERE
    [t1].[e] IS NULL
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73025646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档