在使用 EF 加入数据库 table 时使用 class

Using a class in joining to database table with EF

如果我有一些我需要的对象的摘要 class(例如它的主键等),有没有办法在我需要时使用那个 class 对象的列表编写与其他 table 的连接?所以我的 LINQ 查询中的所有内容都是真实的 table 就像 this.Context.MyTable 但其中之一是我的 List<MyClass> ? 或者是否有任何与 LINQ 相关的 Nuget 项目使这成为可能?

EF LINQ 查询实际上不是 C# 中的 运行 代码,它们在数据库服务器上被转换为 SQL 和 运行;所以你不能用内存数组(或List<T>)加入它们。您可以做的是像这样使用 Contains

public IEnumerable<Table1> GetThingsFromDatabse(DataContext db, IList<MyObject> objects)
{
    var ids = objects.Select(x => x.Id).ToList();
    var results = Enumerable.ToList(
        from x in db.Table1s
        where ids.Contains(x.Id)
        select x
    );

    return results;
}

这被翻译成 SQL 看起来像这样:

SELECT *
FROM [Table1] x
WHERE x.Id IN (@Id1, @Id2, ...)