Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic LINQ - Unable to convert between GUID and string

Tags:

c#

linq

I am dynamically building a LINQ statement. The LINQ statement that I'm building is used purely 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 gets executed, I receive an error that says:

Operator '==' incompatible with operand types 'Guid?' and 'String'

How do I remedy this problem?

Thank you!

like image 766
JQuery Mobile Avatar asked Feb 24 '12 19:02

JQuery Mobile


3 Answers

Works for me without parameter

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

With "Value" doesn't work. Error apear

"{No property or field 'Value' exists in type 'Guid' (at index 3)}"

like image 197
Michał S. Avatar answered Oct 12 '22 22:10

Michał S.


For GUID comparison with dynamic linq use query properties and the Equals() method like in the provided sample.

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();
like image 32
Michael Sander Avatar answered Oct 12 '22 22:10

Michael Sander


For a nullable value, something like this would work:

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

but it's obviously a rather specific case.

The PredicateBuilder by Albahari might be a better solution altogether.

like image 40
Groo Avatar answered Oct 12 '22 22:10

Groo