c# - 合并从不同表投影到一个实体的两个可查询对象

标签 c# linq entity-framework merge iqueryable

我试过了This answer , This onethis one合并两个可查询对象。但我总是收到以下错误:

The type 'Estudio' appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order.

我使用以下代码从两个不同但相似的 Entity Framework 实体(EXAMEN 和 EXPLORACION)映射到我的域实体 Estudio。

IQueryable<Estudio> listExamen = context.Set<EXAMEN>().Project().To<Estudio>();
IQueryable<Estudio> listExploracion = context.Set<EXPLORACION>().Project().To<Estudio>();

var listCombined = listExamen.Concat(listExploracion);

是否有通过合并两个列表生成 IQueryable(不可枚举)的方法?如果使用 AsEnumerable(),则会在内存中执行以下过滤器(Order、Take 等)。所以我需要合并列表,但仍然能够在不执行查询的情况下将过滤器应用于合并列表。

//This will force the next condition is executed on memory
    var listCombined = listExamen.AsEnumerable().Concat(listExploracion);

这可能吗?

最佳答案

我会尝试在您的 linq 查询中将您的数据选择为匿名类型,执行合并,然后添加您的条件。

var listExamen = context.Examen
    .Select(x => new { x.Prop1, x.Prop2, ... }); // Add properties

var listExploracion = context.Exploraction
    .Select(x => new { x.Prop1, x.Prop2, ... }); // Add identical properties

var listCombined = listExamen.Concat(listExploracion);

var whereAdded = listCombines
    .Where(x => x.Prop1 == someValue);
var result = whereAdded
    .Skip(skipCount)
    .Take(takeCount)
    .ToList();

注意:我不知道您是否可以将公用表表达式(跳过/获取的 SQL 必要性)与联合查询结合使用

注意:我已经更改了用于创建表达式的方法,因为我不知道您的方法(ProjectTo)

所以我认为解决方案不是转换为特定类型,而是转换为匿名类型,因为这可能可以转换为 SQL。

警告:没有测试过

关于c# - 合并从不同表投影到一个实体的两个可查询对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22810555/

相关文章:

C# 查找所有没有泛型类型的类实现接口(interface)

c# - LINQ 查询未以字符串形式返回所需结果。为什么?

asp.net - DbContext VS ObjectContext

c# - Code First 导航属性被保留但未加载

javascript - 显示巨大二维数组的最佳方式

c# - 使用 SendKeys 发送特殊字符

c# - Linq 选择所有项目匹配数组

c# - 如何一劳永逸地停止 Entity Framework 6 中的迁移?

c# - 查找 Dns.GetHostEntry 返回的正确 IP 地址

c# - F# 在管道运算符 aka C# LINQ let 中使用临时变量