If you are looking for a function that you can use to bind to a company identifier, check your expression if there is a company entity 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),
Expression.Constant(propertyValue)
),
expression.Body
),
expression.Parameters
);
}
You can use it as follows:
public T First<T>(Expression<Func<T, bool>> expression, int companyId)
{
var set = GetObjectSet<T>();
return set.FirstOrDefault<T>(CheckPropertyIfExists(expression, "CompanyId", companyId));
}
First , .
, , ( 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),
Expression.Constant(propertyValue)
),
parameter
);
return query.Where(predicate);
}
, LINK stanard ( , ).
. :
from x in repository.Clients.FilterByPropertyIfExists("Company", 5)
where x == ???
select x.Name;
[EDIT]
( , ), ObjectQuery ( ObjectQuery 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,
null,
typeof(TProperty),
Type.EmptyTypes,
null
);
if (property == null || !property.CanRead)
return query;
var parameter = Expression.Parameter(typeof(T), "it");
Expression<Func<T, bool>> predicate = (Expression<Func<T, bool>>)Expression.Lambda(
Expression.Equal(
Expression.MakeMemberAccess(parameter, property),
Expression.Constant(propertyValue)
),
parameter
);
return query.Where(predicate);
}
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;
}
}