Saleh
Saleh

Reputation: 3032

A Problem in Linq expression

What is wrong with this code ? I got this exception on the last line:

Unable to create a constant value of type 'System.Collections.Generic.IEnumerable`1'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.

var query = from colT in dal.TBL_Gharardad 
            select colT;  

if(lstTarafeGharardadIds.Count>0)
    query = from q in query 
            join id in lstTarafeGharardadIds on q.TarafeGharardadId equals id 
            select q;

dgvListeGharardad.DataSource = query.ToList();

The lastTarafeGharardadIds is a List<int>

I also test

dgvListeGharardad.DataSource = query;

Everything works well if if expression equals to false and this code

query = from q in query 
        join id in lstTarafeGharardadIds on q.TarafeGharardadId equals id 
        select q;

doesn't run. But I can't understand I got the error on the last line (on this code):

dgvListeGharardad.DataSource = query.ToList();

Upvotes: 0

Views: 141

Answers (2)

Polity
Polity

Reputation: 15150

Wow, thats hard to read!

Anyways, assuming your naming convention is right. you end up with: select colV. Selecting a column results in selecting a IEnumerable rather then a primitive value which your dataSource requires.

You can try and use SelectMany to select the actual value you need

dgvListeGharardad.DataSource = query.SelectMany(x => x.[YourProperty]).ToList();

Upvotes: 0

Maciej Rogoziński
Maciej Rogoziński

Reputation: 677

I think linq can't join between an in-memory collection (lstTarafeGharardadIds) and a database table (dal.TBL_Gharardad, dal.v_Gharardad...).

Similar problem: Why won't this LINQ join statement work?

This should work:

var query = (from colT in dal.TBL_Gharardad select colT).AsEnumerable();;
if (lstTarafeGharardadIds.Count>0)
    query = from q in query 
            join id in lstTarafeGharardadIds on q.TarafeGharardadId equals id 
            select q;
dgvListeGharardad.DataSource = query.ToList();

Upvotes: 2

Related Questions