如何将List <mytableobject>用作LINQ查询的一部分?

时间:2018-08-15 12:11:58

标签: c# entity-framework linq

我有这个LINQ查询:

myDataObject.period = (from pe in myDataObject.myEDMXDataObject.MyTable
    join product in myDataObject.products
    on pe.ID equals product.ID
    where pe.LangID == myDataObject.chosenLang.LangID
    select pe).Distinct().ToList();

myDataObject.products的类型为

List<MyDataObject> products;

我通过带有join和where子句的类似LINQ查询获得myDataObject.products,

myDataObject.products = (from tbl in MyTableName
    join tbl2 in MyTableName2
    on tbl1.ID equals tbl2.ID
    where /* where conditions here */
    select tbl).ToList();

它正常工作。但是我想保持我的代码整洁,所以我不想将所有这些条件再次运行并再次运行联接,而是希望将已经找到的数据传递到下一个LINQ查询中。

我遇到这样的错误:

A first chance exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll

具有内部异常:

Unable to create a constant value of type 'MyWPFApp.MyTableName'. Only primitive types or enumeration types are supported in this context.

当然,错误很明显,我在做不允许的事情。

如何将一个LINQ查询的结果作为另一个LINQ查询的一部分发送?

1 个答案:

答案 0 :(得分:1)

当您应该使用JOIN时,您正在使用WHERE

// select the distinct IDs 
var productIds = myDataObject.products.Select(x => x.ID).Distinct().ToList();

myDataObject.period = myDataObject.myEDMXDataObject.MyTable
    .Where(pe => pe.LangID == myDataObject.chosenLang.LangID
              && productIds.Contains(pe.ID))
    .Distinct()
    .ToList();