How to include an And() Expression that checks for

2019-03-31 22:02发布

问题:

I'd like to add a check in our repository that filters all objects out on a companyId if it's there and if it matches a given value.

So where we have:

public T First<T>(Expression<Func<T, bool>> expression) where T : EntityObject  
{  
   var set = GetObjectSet<T>();  
   return set.FirstOrDefault<T>();  
}  

I would like to add line which looks something where...

express.And("Check for CompanyId property if it exists then make sure it = 3");  

Any ideas on how to go about this?
Thanks :)

回答1:

If you're looking for a function which you can use to tack on a company id check to your expression if a company id exists on the entity, this should do the trick:

public static Expression<Func<T, bool>> CheckPropertyIfExists<T, TProperty>(Expression<Func<T, bool>> expression, string propertyName, TProperty propertyValue)
{
    Type type = typeof(T);
    var property = type.GetProperty(propertyName, typeof(TProperty));
    if(property == null || !property.CanRead)
        return expression;

    return expression.Update(
        Expression.And( // && 
            Expression.Equal( // ==
                Expression.MakeMemberAccess(expression.Parameters[0], property), // T parameter.{propertyName}
                Expression.Constant(propertyValue) // specified propertyValue constant
            ),
            expression.Body // Original expression
        ),
        expression.Parameters
    );
}

You could use it like this:

public T First<T>(Expression<Func<T, bool>> expression, int companyId)
{
    var set = GetObjectSet<T>();  
    return set.FirstOrDefault<T>(CheckPropertyIfExists(expression, "CompanyId", companyId));  
}

And now you can call your First method with your expression and the companyId you want to filter by.

A slightly better way to do this might be to use it as a filtering method, i.e. rewrite it as an extension method that doesn't require an inner expression and works on an object query (or IQueryable):

public static ObjectQuery<T> FilterByPropertyIfExists<T, TProperty>(this ObjectQuery<T> query, string propertyName, TProperty propertyValue)
{
    Type type = typeof(T);
    var property = type.GetProperty(propertyName, typeof(TProperty));
    if(property == null || !property.CanRead)
        return query;

    var parameter = Expression.Parameter(typeof(T), "x");
    Expression<Func<T, bool>> predicate = (Expression<Func<T, bool>>)Expression.Lambda(
        Expression.Equal( // ==
            Expression.MakeMemberAccess(parameter, property), // T parameter.{propertyName}
            Expression.Constant(propertyValue) // specified propertyValue constant
        ),
        parameter
    );
    return query.Where(predicate);
}

The beauty of this is that it will work really nicely with the stanard LINQ syntaxes (both query and fluent).

e.g. it allows queries like this:

from x in repository.Clients.FilterByPropertyIfExists("Company", 5)
where x == ???
select x.Name;

[EDIT]

I've cleaned it up a bit and added a check on parameter visibility (must be a public, static property), as well as an ObjectQuery implementation (which will be automatically used for ObjectQuery and ObjectSet):

public static class QueryExtensions
{
    public static IQueryable<T> FilterByPropertyIfExists<T, TProperty>(this IQueryable<T> query, string propertyName, TProperty propertyValue)
    {
        Type type = typeof(T);
        var property = type.GetProperty(
            propertyName, 
            BindingFlags.Instance | BindingFlags.Public, // Must be a public instance property
            null, 
            typeof(TProperty), // Must be of the correct return type
            Type.EmptyTypes, // Can't have parameters
            null
        );
        if (property == null || !property.CanRead) // Must exist and be readable
            return query; // Return query unchanged

        // Create a predicate to pass to the Where method
        var parameter = Expression.Parameter(typeof(T), "it");
        Expression<Func<T, bool>> predicate = (Expression<Func<T, bool>>)Expression.Lambda(
            Expression.Equal( // ==
                Expression.MakeMemberAccess(parameter, property), // T parameter.{propertyName}
                Expression.Constant(propertyValue) // specified propertyValue constant
            ),
            parameter
        );
        return query.Where(predicate); // Filter the query
    }

    public static ObjectQuery<T> FilterByPropertyIfExists<T, TProperty>(this ObjectQuery<T> query, string propertyName, TProperty propertyValue)
    {
        var filteredQuery = FilterByPropertyIfExists((IQueryable<T>)query, propertyName, propertyValue);
        return (ObjectQuery<T>)filteredQuery; // Cast filtered query back to an ObjectQuery
    }
}


回答2:

Looks like a good candidate for an interface to stay away from reflection:

public interface ICompanyFilterable
{
  int CompanyId { get; set; }
}

public partial class YourEntity : ICompanyFilterable
{
    ....
}

public static IQueryable<T> FilterByCompanyId<T>(this IQueryable<T> query, int companyId)
    where T : ICompanyFilterable
{
    return query.Where(e => e.CompanyId == companyId);
}


回答3:

Bennor, Thanks so much your posting was VERY useful.

I took what you put in there and created an extension method which appends the 'And' filter to the existing expression.

    public static Expression<Func<T, bool>> AddEqualityCheck<T, TProperty>(this Expression<Func<T, bool>> expression, string propertyName, TProperty propertyValue)
    {
        Type type = typeof(T);
        var property = type.GetProperty(
            propertyName,
            BindingFlags.Instance | BindingFlags.Public,
            null,
            typeof(TProperty),
            Type.EmptyTypes,
            null
        );

        if (property == null || !property.CanRead)
        {
            return expression;
        }
        else
        {
            var equalityExpression = Expression.Equal(
                Expression.MakeMemberAccess(expression.Parameters[0], property),
                Expression.Constant(propertyValue)
                );
            var andEqualityExpression = Expression.And(equalityExpression, expression.Body);
            return expression.Update(andEqualityExpression, expression.Parameters);
        }
    }