Search code examples
c#sql-serverentity-frameworkreflectionexpression-trees

Expression to compare Guid properties versus String values and then translate to TSQL


Im working with an very basic expression tree generator to create SQL expressions.

For example, to create an expression for an hypothetical class User comparing an String property called "Name" vs. an String value "john", I use a piece of code similar to this:

var propertyInfo = typeOf(User).GetProperties().First(p=>p.Name=="Name");

Expression.Call(
    Expression.Property(Expression.Parameter(typeof(User), "val"), propertyInfo), 
    typeof(string).GetMethod("Contains"), 
    Expression.Constant("john")
)

Which generates (after some lines of code and EF intervention) something similar to:

[...] Name LIKE '%john%' [...]

My problem is with Guid properties...

I cannot figurate how should construct the expression to compare a Guid property vs. an String value, to generate a very simple SQL query similar to :

[...] Id='38EB4D06-E50B-4C7A-80FF-A6350051682A' [...]

I cannot use the Equals method between Guid and String... Im really clueless, any suggestion will be well received...


Solution

  • This should work:

        var propertyInfo = typeof(Entity).GetProperties().First(p => p.Name == "Id");       
    
        var paramExpr = Expression.Parameter(typeof(Entity));
        var propertyAccessExpr = Expression.MakeMemberAccess(paramExpr, propertyInfo);
        var guidExpr = Expression.Constant(Guid.Parse("38EB4D06-E50B-4C7A-80FF-A6350051682A"));
        var body = Expression.Equal(propertyAccessExpr, guidExpr);
        var lambda = Expression.Lambda<Func<Entity, bool>>(body, paramExpr);
    
        Console.WriteLine(lambda); // Param_0 => (Param_0.Id == 38eb4d06-e50b-4c7a-80ff-a6350051682a)
    

    where Entity is:

    public class Entity
    {
        public Guid Id { get; set; }
    }
    

    Fiddle.