开发者

A Problem in Linq expression

开发者 https://www.devze.com 2023-03-07 05:05 出处:网络
What is wrong with this code ? I got this exception on the last line: Unable to create a constant value of

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 expre开发者_运维问答ssion 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();


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


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

精彩评论

暂无评论...
验证码 换一张
取 消