【问题标题】:Joining two IQueryable variables of different types together using LINQ使用 LINQ 将两个不同类型的 IQueryable 变量连接在一起
【发布时间】:2012-06-25 13:18:04
【问题描述】:

列名称和类型相同,但它来自两个独立的实体。这是一个简化的例子:

--Query View
var v_res = from s in db.V_CMUCUSTOMER
           select s;

--Values from table less values from view
var res = from s in db.CMUCUSTOMERs
          where !(from v in v_res
            select v.ID).Contains(s.ID)
         select s;

--join table and view values into one variable
var res_v_res = (from c in res
            select c).Union(from v in v_res
            select v);

我收到以下错误:

实例参数:无法从“System.Linq.IQueryable”转换为 System.Linq.ParallelQuery

【问题讨论】:

  • 我敢打赌,如果你停止使用 'var',答案就会很清楚。通过让编译器选择 v_res 和 res 的类型,您可以接受它的选择。
  • 编译器可能会为这些变量之一选择一个意外的类型,然后它可能会根据该选择在不同的 Union 实现之间进行选择(System.Linq.Enumerable.Union , System.Linq.Queryable.Union列举两种可能性)。相反,如果你指定了类型,编译器会在你要求不可能的时候告诉你。
  • 如果显式调用Union 方法,即Enumerable.Union(from c in res select c, from v in v_res select v),是否会出现同样的错误?
  • 我得到以下信息:方法 'System.Linq.Enumerable.Union(System.Collections.Generic.IEnumerable, System.Collections.Generic.IEnumerable 的类型参数>)' 无法从用法中推断出来。
  • 您在哪里拨打AsParallel()ParallelQuery 是使用它的结果,但我在上面的代码中没有看到它。

标签: c# linq entity-framework


【解决方案1】:

如果您指定一个新的匿名类型并为两者使用 ToList() 那么您应该能够将它们联合如下:

var v_res = (from s in db.V_CMUCUSTOMER
            select new { custName = s.customer_name custAddress = s.address}).ToList();

--Values from table less values from view
var res = (from s in db.CMUCUSTOMERs
          where !(from v in v_res
            select v.ID).Contains(s.ID)
          select new { custName = s.customer_name custAddress = s.address }).ToList();

--join table and view values into one variable
var res_v_res = v_res.Union(res);

如果有几十个列,这可能会很麻烦,但仍然可以工作。

【讨论】:

    【解决方案2】:

    当我在 LINQPad 中运行类似查询时,我收到一条错误消息,声称 Contains(s.ID) 中的 s 未在此上下文中定义。

    如果我将&& 替换为where,则所有查询都会成功执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-16
      相关资源
      最近更新 更多