开发者

linq query where int ID belongs to List<int>

开发者 https://www.devze.com 2022-12-17 17:46 出处:网络
I\'m having a problem with a linq que开发者_高级运维ry. I have used this similarly before but i cannot understand what could be wrong now.

I'm having a problem with a linq que开发者_高级运维ry. I have used this similarly before but i cannot understand what could be wrong now.

Errors

The best overloaded method match for 'System.Collections.Generic.List.Contains(int)' has some invalid arguments

Argument '1': cannot convert from 'int?' to 'int' ; refers to the where clause of rTestResults

Code:

List<int> rMTCPlates = (from rP in mDataContext.Plates
                        where rP.SOItem.SONumberID == aSONumber
                        select rP.ID).ToList();

var rTestResults = from rT in mDataContext.TestSamplesViews
                   where rMTCPlates.Contains(rT.PlateID)
                   select rT;  

Any idea whats going on?

Any help appreciated,

Thanks


You can use the null-coalescing operator here:

var rTestResults = from rT in mDataContext.TestSamplesViews 
               where rMTCPlates.Contains(rT.PlateID ?? 0) 
               select rT; 


That's because the ID field is nullable, while the items in the collection are not.

You probably forgot to mark it as not-null in the database so the designer, generated it this way.

Best thing mark in the DB is not-null and refresh data.

Besides, U didn't specify which LINQ you're using, assuming you linq the DB, I am not sure the Contains extension method works in Linq to Sql or Linq to Entities, you might get another NotSupportedException even after you fix the above.

Therefore, either use two queries, the first to access the DB and the second to retrieve you value from the loaded collection, or consider using 'Contains()' workaround using Linq to Entities?.

And if you're using linq-to objects and you don't care about all the trash said above, just use the following:

var rTestResults = from rT in mDataContext.TestSamplesViews  
                   where rT.PlateID.HasValue &&
                       rMTCPlates.Contains(rT.PlateID.Value)  
                   select rT.Value; 


Since the exception in on System.Collections.Generic.List.Contains(int) I can guess that the mDataContext.TestSamplesViews.PlateID is nullable.

If you just want an easyquick fix, and/or you cant change PlateID so it isn't nullable anymore, you can check if it has a value first :

var rTestResults = from rT in mDataContext.TestSamplesViews
                   where (rT.PlateID.HasValue && rMTCPlates.Contains(rT.PlateID))
                   select rT;  
0

精彩评论

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