Я пытаюсь создать динамическое выражение Lambda для прохождения в рамках предприятия where сущности в .net. В частности, мне нужно построить условие, например: < /p>
u => (u.firstname + "" + u.lastname) .contains ("anyval") < /p>
Однако я сталкиваюсь с проблемами в явном создании части (u.firstname + "" + u.lastname) как выражение. Что Я попробовал
1⃣ с помощью Express.call со string.concat
< li> Это приводит к функции SQL с функцией concat () , какая структура объекта не поддерживает в том, где clauses.
< H4> 2⃣ с использованием Expression.Add < /code> к цепочке string concatenation < /h4>
Это создает ((u.firstname + "") + u.lastname) < /code>, который также не работает в рамках сущности. < /li>
< /ul>
var parameter = Expression.Parameter(typeof(ApplicationUser), "u");
var firstNameProperty = Expression.PropertyOrField(parameter, "FirstName");
var lastNameProperty = Expression.PropertyOrField(parameter, "LastName");
var spaceConstant = Expression.Constant(" ");
var plusConstant = Expression.Constant("+");
// Constructing (u.FirstName + " " + u.LastName)
var firstNamePlusSpace = Expression.Call(
typeof(string).GetMethod("Concat", new\[\] { typeof(string), typeof(string) }),
Expression.Call(
typeof(string).GetMethod("Concat", new\[\] { typeof(string), typeof(string) }),
firstNameProperty, plusConstant
),
Expression.Call(
typeof(string).GetMethod("Concat", new\[\] { typeof(string), typeof(string) }),
spaceConstant, lastNameProperty
)
);
var fullNameExpression = Expression.Call(
typeof(string).GetMethod("Concat", new\[\] { typeof(string), typeof(string) }),
firstNamePlusSpace, lastNameProperty
);
// Creating the lambda expression
var lambda = Expression.Lambda\(fullNameExpression, parameter);
// Passing the expression to GetCondition method
return GetCondition\(null, condition, value, lambda);
Helper Methods
private static MemberExpression GetMemberExpression(Expression param, string propertyName)
{
if (propertyName.Contains("."))
{
int index = propertyName.IndexOf(".");
var subParam = Expression.Property(param, propertyName.Substring(0, index));
return GetMemberExpression(subParam, propertyName.Substring(index + 1));
}
return Expression.Property(param, propertyName);
}
private static Expression\ GetCondition\(string propertyName, string condition, string value, Expression\ lambdaExp = null)
{
var parameter = Expression.Parameter(typeof(T), "u");
var property = (lambdaExp == null) ? GetMemberExpression(parameter, propertyName) : lambdaExp.Body;
var constant = Expression.Constant(value);
switch (condition.ToLower())
{
case "contains":
return Expression.Lambda(
Expression.Call(property, nameof(string.Contains), null, constant),
parameter);
case "doesnotcontain":
return Expression.Lambda(
Expression.Not(Expression.Call(property, nameof(string.Contains), null, constant)),
parameter);
case "startswith":
return Expression.Lambda(
Expression.Call(property, nameof(string.StartsWith), null, constant),
parameter);
case "endswith":
return Expression.Lambda(
Expression.Call(property, nameof(string.EndsWith), null, constant),
parameter);
case "=":
return Expression.Lambda(
Expression.Equal(property, constant),
parameter);
default:
return null;
}
}
проблема и ожидаемое поведение Проблема : когда я использую Expression.call с String.concat, Entity Framework не работает Признайте сгенерированный запрос в предложении WHERE. Br /> Возможные решения и обходные пути
Я открыт для решений, независимо от того, включают ли они: < /p>
Правильный способ построения (u.firstname + "" + u. Lastname) в дереве выражения
Любая помощь или предложения были бы очень оценены!
Я пытаюсь создать динамическое выражение Lambda для прохождения в рамках предприятия where сущности в .net. В частности, мне нужно построить условие, например: < /p> u => (u.firstname + "" + u.lastname) .contains ("anyval") < /p> Однако я сталкиваюсь с проблемами в явном создании части (u.firstname + "" + u.lastname) как выражение. [b] Что Я попробовал [/b] [h4] 1⃣ с помощью Express.call со string.concat [/h4] [list] < li> Это приводит к функции SQL с функцией concat () , какая структура объекта не поддерживает в том, где clauses. [/list] < H4> 2⃣ с использованием Expression.Add < /code> к цепочке string concatenation < /h4>
Это создает ((u.firstname + "") + u.lastname) < /code>, который также не работает в рамках сущности. < /li> < /ul> [code]var parameter = Expression.Parameter(typeof(ApplicationUser), "u"); var firstNameProperty = Expression.PropertyOrField(parameter, "FirstName"); var lastNameProperty = Expression.PropertyOrField(parameter, "LastName"); var spaceConstant = Expression.Constant(" "); var plusConstant = Expression.Constant("+");
switch (condition.ToLower()) { case "contains": return Expression.Lambda( Expression.Call(property, nameof(string.Contains), null, constant), parameter); case "doesnotcontain": return Expression.Lambda( Expression.Not(Expression.Call(property, nameof(string.Contains), null, constant)), parameter); case "startswith": return Expression.Lambda( Expression.Call(property, nameof(string.StartsWith), null, constant), parameter); case "endswith": return Expression.Lambda( Expression.Call(property, nameof(string.EndsWith), null, constant), parameter); case "=": return Expression.Lambda( Expression.Equal(property, constant), parameter); default: return null; }
} [/code] [b] проблема и ожидаемое поведение [/b] [b] Проблема [/b]: когда я использую Expression.call с String.concat, Entity Framework не работает Признайте сгенерированный запрос в предложении WHERE. Br /> Возможные решения и обходные пути Я открыт для решений, независимо от того, включают ли они: < /p> Правильный способ построения [b] (u.firstname + "" + u. Lastname) [/b] в дереве выражения Любая помощь или предложения были бы очень оценены!