Dynamic LINQ - Cannot Convert Between GUID and String

I am dynamically creating a LINQ statement. The LINQ statement that I create is used exclusively for the WHERE clause.

string[] values = GetPropertyValues(); 
string propertyName = GetPropertyName();

string clause = string.Empty;
if (values.Length > 0)
  clause = propertyName + "==\"" + values[0] + "\"";

From what I can tell, my LINQ query looks correct. But when it runs, an error message appears:

The operator '==' is not compatible with the operand types 'Guid?' and 'String'

How do I solve this problem?

Thank!

+5
source share
5 answers

It looks like the property returned by GetPropertyName () is of type Guid (I think from an error), but you are trying to compare it with the contents of the values ​​[0], which you declare as a string.

Dynamic Linq allows you to define parameters in the where clause so you can do

string clause = propertyName + "= @1";
LambdaExpression expr = Dynamic.ParseLambda( typeof(YourType), typeof(bool), clause, values[0]);

YourType - IQueryable. , , IQueyable<Customer>, YourType Customer. , propertyName.

, Dynamic Linq , - YourType propertyName. , , - , .Where().

0

GUID linq Equals(), .

var items = new[]
            {
                new { Id = Guid.Empty },
                new { Id = Guid.NewGuid() },
                new { Id = Guid.NewGuid() }
            };

var result = items.AsQueryable()
    .Where("Id.Equals(@0)", Guid.Empty)
    .Any();
+5

"Id.Equals(Guid(\"D243372F-7ED0-40E6-B93D-6165F7521C29\"))"

"Value" .

"{ " " " Guid "( 3)}"

+5

- :

clause = "Id.Value.ToString()==\"a\""; /* Id is of type Guid? */

, , .

PredicateBuilder from Albahari may be the best solution overall.

+3
source

If you don't want to pass guid as a parameter, you can use it to compare strings and pointers:

clause = "Id.Value.Equals(Guid(\"" + values[0] + "\"))";

It works.

... Or this is in your example:

clause = propertyName + ".Value.Equals(\"" + values[0] + "\")";
0
source

All Articles