Creating a LINQ Expression where parameter equals object

前端 未结 3 1033
野性不改
野性不改 2021-02-07 00:18

Given a primitive value age I know how to create an expression like this:

//assuming: age is an int or some other primitive type
employee => empl         


        
3条回答
  •  清歌不尽
    2021-02-07 00:58

    In addition to what has been mentioned in previous answers. A more specific solution would go as such:

    public static Expression CreateExpression(string propertyName, object valueToCompare)
    {
        // get the type of entity
        var entityType = typeof(T);
        // get the type of the value object
        var valueType = valueToCompare.GetType();
        var entityProperty = entityType.GetProperty(propertyName);
        var propertyType = entityProperty.PropertyType;
    
    
        // Expression: "entity"
        var parameter = Expression.Parameter(entityType, "entity");
    
        // check if the property type is a value type
        // only value types work 
        if (propertyType.IsValueType || propertyType.Equals(typeof(string)))
        {
            // Expression: entity.Property == value
            return Expression.Equal(
                Expression.Property(parameter, entityProperty),
                Expression.Constant(valueToCompare)
            );
        }
        // if not, then use the key
        else
        {
            // get the key property
            var keyProperty = propertyType.GetProperties().FirstOrDefault(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Length > 0);
    
            // Expression: entity.Property.Key == value.Key
            return Expression.Equal(
                Expression.Property(
                    Expression.Property(parameter, entityProperty),
                    keyProperty
                ),
                Expression.Constant(
                    keyProperty.GetValue(valueToCompare),
                    keyProperty.PropertyType
                )
            );
        }
    }
    

    IMPORTANT POINTS :

    1. Make sure to check for nulls
    2. Make sure propertyType and valueType are compatible (either they are the same type or are convertible)
    3. Several assumptions are made here (e.g. that you do assign a KeyAttribute)
    4. This code is not tested, so it is not exactly copy/paste ready.

    Hope that helps.

提交回复
热议问题