I've got such expression:
Linq2Rest.Reactive.InnerRestObservable`1[A]
.Where(item => (Convert(IIF((item != null), item.ID, 0)) == Convert(61)))
.Skip(0)
.Take(20)
When I invoke Subscribe method on it I recieve such error:
variable 'item' of type 'A' referenced from scope '', but it is not defined
Can't figure out what is the problem. Actually can't see any problems with item argument...
UPD.
Where clause built with this code:
public static IQbservable WhereExpression(this IQbservable query, Expression filterExpression, ParameterExpression instance = null)
{
if (instance == null)
instance = Expression.Parameter(query.ElementType, "item"); // NOI18N
var filteredQuery = (IQbservable)GenericsHelper.InvokeGenericExtensionMethod(
typeof(Qbservable),
"Where", // NOI18N
new[] { query.ElementType },
query,
Expression.Lambda(filterExpression, instance)
);
return filteredQuery;
}
public static object InvokeGenericExtensionMethod(
Type extensionClass,
string extensionMethodName,
Type[] genericTypes,
params object[] parameters
)
{
var method = extensionClass.GetMethods().FirstOrDefault(m =>
m.Name == extensionMethodName &&
m.IsGenericMethod &&
m.GetGenericArguments().Length == genericTypes.Length &&
m.GetParameters().Length == parameters.Length
);
if (method == null)
throw new ArgumentException(string.Format("Type {0} doesn't contain method {1}", extensionClass.Name, extensionMethodName)); // NOI18N
var genericMethod = method.MakeGenericMethod(genericTypes);
return genericMethod.Invoke(null, parameters);
}
UPD 2. This is how WhereExpression calls:
foreach (var filter in filters)
{
var paramExpression = Expression.Parameter(query.ElementType, "item"); // NOI18N
query = query.WhereExpression(filter.CreateFilterExpression(paramExpression), paramExpression);
}
filters is collection of IFilterDescriptor interface from telerik.
You need to use the same ParameterExpression instance both as the parameter and in the body of the expression.
The easiest thing would be to simply use the one from the filter expression, by using it completely.
Related
Is it possible to get elements in a sqlite table from a string with the name of the table (using Entity Framework)? How?
And how can I get only the value of a property? (I need to get a list of IDs to create a in html that's used to choose which element in a table the user wants to delete)
using using Microsoft.EntityFrameworkCore;
public static List<string> GetAllIdsFromTableName(string tableName)
{
var db = new dbContext();
// What I would like to do:
// return db.tableName.Select(x => x.id).ToList<string>();
}
The following extension returns IQueryable<string> and you can materialise arrays, lists, or you can do it asynchronously:
var result = context.GetAllIdsFromTable("SomeTable", "Id")
.ToList();
And implementation:
public static class QueryableExtensions
{
private static readonly MethodInfo _toStringMethod = typeof(Convert).GetMethods()
.Single(m =>
m.Name == nameof(Convert.ToString) && m.GetParameters().Length == 1 &&
m.GetParameters()[0].ParameterType == typeof(object)
);
public static IQueryable<string> GetAllIdsFromTable(this DbContext ctx, string tableName, string idColumnName = "Id")
{
var model = ctx.Model;
var entityType = model.GetEntityTypes().FirstOrDefault(et =>
tableName.Equals(et.GetTableName(), StringComparison.InvariantCultureIgnoreCase));
if (entityType == null)
throw new InvalidOperationException($"Entity for table '{tableName}' not found.");
// GetColumnName() can be obsolete, it depends on EF Core version.
var prop = entityType.GetProperties().FirstOrDefault(p =>
idColumnName.Equals(p.GetColumnName(), StringComparison.InvariantCultureIgnoreCase));
if (prop == null)
throw new InvalidOperationException($"Property for column '{tableName}'.'{idColumnName}' not found.");
var entityParam = Expression.Parameter(entityType.ClrType, "e");
var ctxParam = Expression.Parameter(typeof(DbContext), "ctx");
// ctx.Set<entityType>()
var setQuery = Expression.Call(ctxParam, nameof(DbContext.Set), new[] { entityType.ClrType });
Expression propExpression;
if (prop.PropertyInfo == null)
// 'prop' is Shadow property, so call via EF.Property(e, "name")
propExpression = Expression.Call(typeof(EF), nameof(EF.Property), new[] { prop.ClrType },
entityParam, Expression.Constant(prop.Name));
else
propExpression = Expression.MakeMemberAccess(entityParam, prop.PropertyInfo);
propExpression = EnsureString(propExpression);
// e => e.Prop
var propLambda = Expression.Lambda(propExpression, entityParam);
// ctx.Set<entityType>().Select(e => e.Prop)
Expression selectAll = Expression.Call(typeof(Queryable), nameof(Queryable.Select),
new[] { entityType.ClrType, typeof(string) },
setQuery, Expression.Quote(propLambda));
var constructQuery = Expression.Lambda<Func<DbContext, IQueryable<string>>>(selectAll, ctxParam);
return constructQuery.Compile()(ctx);
}
private static Expression EnsureString(Expression expression)
{
if (expression.Type == typeof(string))
return expression;
if (expression.Type != typeof(object))
expression = Expression.Convert(expression, typeof(object));
expression = Expression.Call(_toStringMethod, expression);
return expression;
}
}
Is there any way to apply "HasQueryFilter" globaly to all my entity ? I don't want
to add in modelbuilder one by one ?
modelBuilder.Entity<Manufacturer>().HasQueryFilter(p => p.IsActive);
In case you have base class or interface defining the IsActive property, you could use the approach from Filter all queries (trying to achieve soft delete).
Otherwise you could iterate entity types, and for each type having bool IsActive property build dynamically filter expression using Expression class methods:
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
var isActiveProperty = entityType.FindProperty("IsActive");
if (isActiveProperty != null && isActiveProperty.ClrType == typeof(bool))
{
var parameter = Expression.Parameter(entityType.ClrType, "p");
var filter = Expression.Lambda(Expression.Property(parameter, isActiveProperty.PropertyInfo), parameter);
entityType.QueryFilter = filter;
}
}
Update (EF Core 3.0): Due to public metadata API breaking change (replacing many properties with Get / Set extension methods), the last line becomes
entityType.SetQueryFilter(filter);
For those looking to implement Ivan's answer in EF Core 3.0, note the necessary change in the last line:
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
var isActiveProperty = entityType.FindProperty("IsActive");
if (isActiveProperty != null && isActiveProperty.ClrType == typeof(bool))
{
var parameter = Expression.Parameter(entityType.ClrType, "p");
var filter = Expression.Lambda(Expression.Property(parameter, isActiveProperty.PropertyInfo), parameter);
MutableEntityTypeExtensions.SetQueryFilter(entityType, filter);
}
}
Here is extention method for EF Core version 6
public static void ApplySoftDeleteQueryFilter(this ModelBuilder modelBuilder)
{
var entityTypes = modelBuilder.Model
.GetEntityTypes();
foreach (var entityType in entityTypes)
{
var isActiveProperty = entityType.FindProperty("IsActive");
if (isActiveProperty != null && isActiveProperty.ClrType == typeof(bool))
{
var entityBuilder = modelBuilder.Entity(entityType.ClrType);
var parameter = Expression.Parameter(entityType.ClrType, "e");
var methodInfo = typeof(EF).GetMethod(nameof(EF.Property))!.MakeGenericMethod(typeof(bool))!;
var efPropertyCall = Expression.Call(null, methodInfo, parameter, Expression.Constant("IsActive"));
var body = Expression.MakeBinary(ExpressionType.Equal, efPropertyCall, Expression.Constant(true));
var expression = Expression.Lambda(body, parameter);
entityBuilder.HasQueryFilter(expression);
}
}
}
I try to perform a simple LIKE action on the database site, while having query building services based on generic types. I found out while debugging however, that performing EF.Functions.Like() with reflection does not work as expected:
The LINQ expression 'where __Functions_0.Like([c].GetType().GetProperty("FirstName").GetValue([c], null).ToString(), "%Test%")' could not be translated and will be evaluated locally..
The code that makes the difference
That works:
var query = _context.Set<Customer>().Where(c => EF.Functions.Like(c.FirstName, "%Test%"));
This throws the warning & tries to resolve in memory:
var query = _context.Set<Customer>().Where(c => EF.Functions.Like(c.GetType().GetProperty("FirstName").GetValue(c, null).ToString(), "%Test%"));
Does the Linq query builder or the EF.Functions not support reflections?
Sorry if the questions seem basic, it's my first attempt with .NET Core :)
In EF the lambdas are ExpressionTrees and the expressions are translated to T-SQL so that the query can be executed in the database.
You can create an extension method like so:
public static IQueryable<T> Search<T>(this IQueryable<T> source, string propertyName, string searchTerm)
{
if (string.IsNullOrEmpty(propertyName) || string.IsNullOrEmpty(searchTerm))
{
return source;
}
var property = typeof(T).GetProperty(propertyName);
if (property is null)
{
return source;
}
searchTerm = "%" + searchTerm + "%";
var itemParameter = Parameter(typeof(T), "item");
var functions = Property(null, typeof(EF).GetProperty(nameof(EF.Functions)));
var like = typeof(DbFunctionsExtensions).GetMethod(nameof(DbFunctionsExtensions.Like), new Type[] { functions.Type, typeof(string), typeof(string) });
Expression expressionProperty = Property(itemParameter, property.Name);
if (property.PropertyType != typeof(string))
{
expressionProperty = Call(expressionProperty, typeof(object).GetMethod(nameof(object.ToString), new Type[0]));
}
var selector = Call(
null,
like,
functions,
expressionProperty,
Constant(searchTerm));
return source.Where(Lambda<Func<T, bool>>(selector, itemParameter));
}
And use it like so:
var query = _context.Set<Customer>().Search("FirstName", "Test").ToList();
var query2 = _context.Set<Customer>().Search("Age", "2").ToList();
For reference this was the Customer I used:
public class Customer
{
[Key]
public Guid Id { get; set; }
public string FirstName { get; set; }
public int Age { get; set; }
}
Simple answer, no.
EntityFramework is trying to covert your where clause in to a SQL Query. There is no native support for reflection in this conversation.
You have 2 options here. You can construct your text outside of your query or directly use property itself. Is there any specific reason for not using something like following?
var query = _context.Set<Customer>().Where(c => EF.Functions.Like(c.FirstName, "%Test%"));
Keep in mind that every ExpresionTree that you put in Where clause has to be translated into SQL query.
Because of that, ExpressionTrees that you can write are quite limited, you have to stick to some rules, thats why reflection is not supported.
Image that instead of :
var query = _context.Set<Customer>().Where(c => EF.Functions.Like(c.GetType().GetProperty("FirstName").GetValue(c, null).ToString(), "%Test%"));
You write something like:
var query = _context.Set<Customer>().Where(c => EF.Functions.Like(SomeMethodThatReturnsString(c), "%Test%"));
It would mean that EF is able to translate any c# code to SQL query - it's obviously not true :)
I chucked together a version of the accepted answer for those using NpgSQL as their EF Core provider as you will need to use the ILike function instead if you want case-insensitivity, also added a second version which combines a bunch of properties into a single Where() clause:
public static IQueryable<T> WhereLike<T>(this IQueryable<T> source, string propertyName, string searchTerm)
{
// Check property name
if (string.IsNullOrEmpty(propertyName))
{
throw new ArgumentNullException(nameof(propertyName));
}
// Check the search term
if(string.IsNullOrEmpty(searchTerm))
{
throw new ArgumentNullException(nameof(searchTerm));
}
// Check the property exists
var property = typeof(T).GetProperty(propertyName);
if (property == null)
{
throw new ArgumentException($"The property {typeof(T)}.{propertyName} was not found.", nameof(propertyName));
}
// Check the property type
if(property.PropertyType != typeof(string))
{
throw new ArgumentException($"The specified property must be of type {typeof(string)}.", nameof(propertyName));
}
// Get expression constants
var searchPattern = "%" + searchTerm + "%";
var itemParameter = Expression.Parameter(typeof(T), "item");
var functions = Expression.Property(null, typeof(EF).GetProperty(nameof(EF.Functions)));
var likeFunction = typeof(NpgsqlDbFunctionsExtensions).GetMethod(nameof(NpgsqlDbFunctionsExtensions.ILike), new Type[] { functions.Type, typeof(string), typeof(string) });
// Build the property expression and return it
Expression selectorExpression = Expression.Property(itemParameter, property.Name);
selectorExpression = Expression.Call(null, likeFunction, functions, selectorExpression, Expression.Constant(searchPattern));
return source.Where(Expression.Lambda<Func<T, bool>>(selectorExpression, itemParameter));
}
public static IQueryable<T> WhereLike<T>(this IQueryable<T> source, IEnumerable<string> propertyNames, string searchTerm)
{
// Check property name
if (!(propertyNames?.Any() ?? false))
{
throw new ArgumentNullException(nameof(propertyNames));
}
// Check the search term
if (string.IsNullOrEmpty(searchTerm))
{
throw new ArgumentNullException(nameof(searchTerm));
}
// Check the property exists
var properties = propertyNames.Select(p => typeof(T).GetProperty(p)).AsEnumerable();
if (properties.Any(p => p == null))
{
throw new ArgumentException($"One or more specified properties was not found on type {typeof(T)}: {string.Join(",", properties.Where(p => p == null).Select((p, i) => propertyNames.ElementAt(i)))}.", nameof(propertyNames));
}
// Check the property type
if (properties.Any(p => p.PropertyType != typeof(string)))
{
throw new ArgumentException($"The specified properties must be of type {typeof(string)}: {string.Join(",", properties.Where(p => p.PropertyType != typeof(string)).Select(p => p.Name))}.", nameof(propertyNames));
}
// Get the expression constants
var searchPattern = "%" + searchTerm + "%";
var itemParameter = Expression.Parameter(typeof(T), "item");
var functions = Expression.Property(null, typeof(EF).GetProperty(nameof(EF.Functions)));
var likeFunction = typeof(NpgsqlDbFunctionsExtensions).GetMethod(nameof(NpgsqlDbFunctionsExtensions.ILike), new Type[] { functions.Type, typeof(string), typeof(string) });
// Build the expression and return it
Expression selectorExpression = null;
foreach (var property in properties)
{
var previousSelectorExpression = selectorExpression;
selectorExpression = Expression.Property(itemParameter, property.Name);
selectorExpression = Expression.Call(null, likeFunction, functions, selectorExpression, Expression.Constant(searchPattern));
if(previousSelectorExpression != null)
{
selectorExpression = Expression.Or(previousSelectorExpression, selectorExpression);
}
}
return source.Where(Expression.Lambda<Func<T, bool>>(selectorExpression, itemParameter));
}
I'm actually working on a method that select object which at least one property contains one or multiple words.
The construction of the tree seems correct but The MethodCall fails.
Here's the code:
public List<Article> FilterArticle(string expression, ref List<Article> listeArticle)
{
IQueryable<Article> queryableData = listeArticle.AsQueryable();
string[] expressionList = expression.Split(new char[] { ' ' });
Linq.Expression predicate = null;
List<Linq.Expression> predicateList = new List<Linq.Expression>();
int i = 0;
foreach (PropertyInfo property in typeof(Article).GetProperties())
{
foreach (string ex in expressionList)
{
string propertyName = property.Name.ToString();
ParameterExpression parameterEx = Linq.Expression.Parameter(typeof(Article), "objectProperty");
MemberExpression propertyEx = Linq.Expression.Property(parameterEx, propertyName);
MethodInfo toStringMethod = typeof(object).GetMethod("ToString");
MethodInfo containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var value = Linq.Expression.Constant(ex, typeof(string));
Linq.Expression containsMethodExp = Linq.Expression.Call(Linq.Expression.Call(propertyEx, toStringMethod), containsMethod, value);
predicateList.Add(containsMethodExp);
if (i == 0) { predicate = predicateList[i]; }
if (i > 0) predicate = Linq.Expression.Or(predicate, predicateList[i]);
i = i + 1;
}
}
Func<IEnumerable<Article>, Func<Article, bool>, IEnumerable<Article>> whereDelegate = Enumerable.Where;
MethodInfo whereMethodInfo = whereDelegate.Method;
// FAIL
MethodCallExpression methodCallEx = Linq.Expression.Call(whereMethodInfo, predicate);
return queryableData.Provider.CreateQuery<Article>(methodCallEx).ToList();
}
This line:
MethodCallExpression methodCallEx = Linq.Expression.Call(whereMethodInfo, predicate);
Send this error:
An exception of type 'System.ArgumentException' occurred in
System.Core.dll but was not handled in user code
Additional information: Incorrect number of arguments supplied for
call to method
'System.Collections.Generic.IEnumerable1[Colibri.Models.Article]
Where[Article](System.Collections.Generic.IEnumerable1[Colibri.Models.Article],
System.Func`2[Colibri.Models.Article,System.Boolean])
'
Thanks for you help.
I have the following code block I am using to perform some dynamic filtering on a generic IQueryable list
private static MethodInfo miTL = typeof(String).GetMethod("ToLower", Type.EmptyTypes);
public static IQueryable<T> Where<T>(IQueryable<T> source, string member, object value)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (member == null)
{
throw new ArgumentNullException("member");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value is string && !string.IsNullOrWhiteSpace(value.ToString()))
{
//If the type is string, force lowercase equals comparison for both sides.
value = value.ToString().ToLower();
var parameter = Expression.Parameter(typeof(T), "item");
var parameterProperty = Expression.Property(parameter, member);
//ToLower dynamic expression
var dynamicExpression = Expression.Call(parameterProperty, miTL);
var constantValue = Expression.Constant(value);
var equalsExpression = Expression.Equal(dynamicExpression, constantValue);
var lambdaExpression = Expression.Lambda<Func<T, bool>>(equalsExpression, parameter);
return source.Where(lambdaExpression);
}
else
{
var item = Expression.Parameter(typeof(T), "item");
var prop = Expression.Property(item, member);
var soap = Expression.Constant(value);
var equal = Expression.Equal(prop, soap);
var lambda = Expression.Lambda<Func<T, bool>>(equal, item);
return source.Where(lambda);
}
}
This all works fine - apart from the possibility of my source containing null values, which then returns a null reference exception.
It directly translates to (when the field is "Counterparty" :- {item => (item.Counterparty.ToLower() == "name of counterparty")}
What I actually need in Lambda expression form is :-
{item => !string.IsNullEmptyOrWhitespace(item.Counterparty) && (item.Counterparty.ToLower() == "name of counterparty")}
Any ideas how to achieve this dynamically?
--REVIEWED--
Here is the whole replacement code, using a much nicer string.Equals check
public static IQueryable<T> Where<T>(IQueryable<T> source, string member, object value)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (member == null)
{
throw new ArgumentNullException("member");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value is string && !string.IsNullOrWhiteSpace(value.ToString()))
{
var parameter = Expression.Parameter(typeof(T), "item");
var parameterProperty = Expression.Property(parameter, member);
var body =
Expression.AndAlso(
Expression.Not(
Expression.Call(typeof(string), "IsNullOrEmpty", null, parameterProperty)
),
Expression.Call(typeof(string), "Equals", null,
parameterProperty, Expression.Constant(value),
Expression.Constant(System.StringComparison.InvariantCultureIgnoreCase))
);
var body2 = Expression.Call(typeof(string), "Equals", null,
parameterProperty, Expression.Constant(value),
Expression.Constant(System.StringComparison.InvariantCultureIgnoreCase));
var lambdaExpression = Expression.Lambda<Func<T, bool>>(body, parameter);
return source.Where(lambdaExpression);
}
else
{
var item = Expression.Parameter(typeof(T), "item");
var prop = Expression.Property(item, member);
var soap = Expression.Constant(value);
var equal = Expression.Equal(prop, soap);
var lambda = Expression.Lambda<Func<T, bool>>(equal, item);
return source.Where(lambda);
}
}
A literal translation would be something like:
var body =
Expression.AndAlso(
Expression.Not(
Expression.Call(typeof(string), "IsNullOrWhiteSpace", null,
parameterProperty)
),
Expression.Equal(
Expression.Call(parameterProperty, "ToLower", null),
Expression.Constant("name of counterparty")
)
);
However, you would do well to look at the various string.Equals overloads. For example:
var body = Expression.Call(typeof(string), "Equals", null,
parameterProperty, Expression.Constant("name of counterparty"),
Expression.Constant(System.StringComparison.InvariantCultureIgnoreCase));