Vlad
Vlad

Reputation: 2773

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?

Upvotes: 0

Views: 60

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

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

Upvotes: 1

Related Questions