简体   繁体   中英

How to use List<MyTableObject> as a part of LINQ query?

I have this LINQ query:

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();

where myDataObject.products is of type

List<MyDataObject> products;

I get myDataObject.products with a similar LINQ query with join and where clauses, like this

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

It works properly. But I want to keep my code clean so instead of running all those conditions and the join again, I want to pass the data I have found already into the next LINQ query.

I am getting error like this:

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

with inner exception:

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

Of course, the error is clear, I am doing something which is not allowed.

How can I send result from one LINQ query as a part of another LINQ query?

You are using a JOIN when what you should be using is a 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM