Создать динамическое выражение Lambda для (U.FirstName + "" + U.LastName) явно в C#C#

Место общения программистов C#
Ответить
Anonymous
 Создать динамическое выражение Lambda для (U.FirstName + "" + U.LastName) явно в C#

Сообщение Anonymous »

Я пытаюсь создать динамическое выражение 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) в дереве выражения
Любая помощь или предложения были бы очень оценены!

Подробнее здесь: https://stackoverflow.com/questions/793 ... -expliclty
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»