I am facing some problem while executing the query having 'Contains' keyword in Dynamic linq in C#. I am getting the below error
No property or field exists in type 'Int32'
My code is as below:
If I user the 'Contains' keyword for datatype string field, then it works fine as below
string[] CandidateNamesArray = new string[]{"Ram", "Venkat", "Micheal"}
var dynamicLinqQuery = Candidates.Where("CandidateName.Contains(@0)", CandidateNamesArray );
But if I use the 'Contains' keyword for datatype int field, then it throws exception as below
int[] CandidateIdsArray = new int[]{4, 78, 101}
var dynamicLinqQuery = Candidates.Where("CandidateId.Contains(@0)", CandidateIdsArray);
Runtime Exception - "No applicable method 'Contains' exists in type 'Int32'"
Also tried in another way as below
int[] CandidateIdsArray = new int[]{4, 78, 101}
var dynamicLinqQuery = Candidates.Where("@0.Contains(CandidateId)", CandidateIdsArray);
Runtime Exception - "No property or field 'CandidateId' exists in type 'Int32'"
I have spend almost 2 days to resolve the above problem but not able to succeed. Could any one please help me out in resolving the above issue...Thanks in Advance
The Dynamic source file includes a helper library that allows you to express LINQ queries using extension methods that take string arguments instead of type safe operators. To use the Dynamic Expression API, you could simply copy/paste the Dynamic source file in your project.
LINQ Contains is quantifier operator. In LINQ Contains it also checks with the data sources, to check whether the collection of lists contains their desired element or not, and then it returns the result as either true or false based on the expected outcomes of the result.
However, the basic rule is very simple: a LINQ data source is any object that supports the generic IEnumerable<T> interface, or an interface that inherits from it. Types such as ArrayList that support the non-generic IEnumerable interface can also be used as a LINQ data source.
I know it's a long time from your post, but I faced the same issue today.
I solved it using outerIt
before the property inside the Contains
.
In your example:
int[] CandidateIdsArray = new int[]{4, 78, 101}
var dynamicLinqQuery = Candidates.Where("@0.Contains(outerIt.CandidateId)", CandidateIdsArray);
It worked for me because DynamicLinq was thinking CandidateId was a property of the array's object. And using outerIt made it understand that it refers to the outer iterator, which is the Candidate.
I dont know Dynamic Linq but it seems obvious to me that type Int32
does not contain any method called Contains
. How about converting it to a string
before calling Contains
?
var dynamicLinqQuery = Candidates.Where("CandidateId.ToString().Contains(@0)", CandidateIdsArray);
You can use convert your array to string, then make Contains() than convert it back to int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With