I am writing a method which accepts a lambda expression as a parameter and parses its properties from left to right. The following criteria should be met:
The expression must only use simple property or fields -- no method calls or LINQ queries or anything more complex. (e.g. p => p.HomeAddress.City) The method can throw an exception if the expression does not meet these criteria.
The method should return a list of info about each property or field: name and type.
How can this be accomplished?
private List<SomeClass> ParseExpression<T1,T2>(Expression<Func<T1, T2>> func)
{
// ??
}
This:
private static IReadOnlyList<Tuple<string, Type>> ParseExpression<T1, T2>(Expression<Func<T1, T2>> func)
{
var par = func.Parameters[0];
var lst = new List<Tuple<string, Type>>();
Expression exp = func.Body;
while (exp != par)
{
if (exp.NodeType != ExpressionType.MemberAccess)
{
throw new Exception(exp.ToString());
}
MemberExpression me = (MemberExpression)exp;
MemberInfo mi = me.Member;
if (mi.MemberType == MemberTypes.Field)
{
FieldInfo fi = (FieldInfo)mi;
lst.Add(Tuple.Create(fi.Name, fi.FieldType));
}
else if (mi.MemberType == MemberTypes.Property)
{
PropertyInfo pi = (PropertyInfo)mi;
lst.Add(Tuple.Create(pi.Name, pi.PropertyType));
}
else
{
throw new Exception(exp.ToString());
}
exp = me.Expression;
}
lst.Reverse();
return lst;
}
Example:
class Cl1
{
public Cl2 Cl2;
}
class Cl2
{
public string Str { get; set; }
}
and then:
var result = ParseExpression<Cl1, string>(x => x.Cl2.Str);
foreach (var el in result)
{
Console.WriteLine($"{el.Item1}: {el.Item2}");
}
Related
I have created a generic method(NewIfNull) to create an instance of class if object is null. But currently I am supplying the property name as hard-coded which I don't want to do. Please help if there is any way to do this.
static void Main(string[] args)
{
RnD rnD = new RnD();
rnD.NewIfNull("A").A.NewIfNull("B").B.NewIfNull("C");
if(rnD.A.B.C != null)
{
}
}
class RnD
{
public A A { get; set; }
}
class A
{
public B B { get; set; }
}
class B
{
public C C { get; set; }
}
class C
{
}
public static class ExtensionClass1
{
public static T NewIfNull<T>(this T obj, string propName)
{
if (obj != null)
{
if (obj.GetType().GetProperty(propName) != null &&
obj.GetType().GetProperty(propName).GetValue(obj) == null)
{
Type type =
obj.GetType().GetProperty(propName).PropertyType;
if (type.IsClass)
{
var getobj = Activator.CreateInstance(type);
obj.GetType().GetProperty(propName).SetValue(obj,
getobj);
}
}
}
return obj;
}
}
I don't want to pass "A", "B" and "C" as hard-coded in below code.
rnD.NewIfNull("A").A.NewIfNull("B").B.NewIfNull("C");
A simple answer without trying to understand what you are actually trying to do is to use nameof:
rnD.NewIfNull(nameof(RnD.A)).A.NewIfNull(nameof(A.B)).B.NewIfNull(nameof(B.C));
You can use expressions to do this.
public static TProperty NewIfNull<TObj, TProperty>(this TObj obj, Expression<Func<TObj, TProperty>> selector)
{
if (!(selector.Body is MemberExpression memberExpression)
|| !(memberExpression.Member is PropertyInfo propertyInfo))
{
throw new ArgumentException("Expected a lambda in the form x => x.Property", nameof(selector));
}
var property = (TProperty)propertyInfo.GetValue(obj);
if (property == null)
{
// We already know that typeof(TProperty).IsClass is true - if it
// wasn't, then 'property' could not have been null above.
property = (TProperty)Activator.CreateInstance(typeof(TProperty));
propertyInfo.SetValue(obj, property);
}
return property;
}
Then you can call it like:
rnD.NewIfNull(x => x.A).NewIfNull(x => x.B).NewIfNull(x => x.C);
You can quite easily modify it to initialise all of your properties at the same time:
public static void NewIfNull<TObj, TProperty>(this TObj obj, Expression<Func<TObj, TProperty>> selector)
{
object subject = obj;
foreach (var member in GetMembers().Reverse())
{
if (!(member.Member is PropertyInfo propertyInfo))
{
throw new ArgumentException("Member was not a property", nameof(selector));
}
var property = propertyInfo.GetValue(subject);
if (property == null)
{
property = Activator.CreateInstance(propertyInfo.PropertyType);
propertyInfo.SetValue(subject, property);
}
subject = property;
}
IEnumerable<MemberExpression> GetMembers()
{
for (var member = GetMember(selector.Body); member != null; member = GetMember(member.Expression))
{
yield return member;
}
}
MemberExpression GetMember(Expression expr)
{
if (expr is ParameterExpression)
{
return null;
}
if (expr is MemberExpression member)
{
return member;
}
throw new ArgumentException("Expected a lambda in the form x => x.A.B.C", nameof(selector));
}
}
And call it like:
rnD.NewIfNull(x => x.A.B.C);
I want to sort my columns on the base of column name which is a string but unfortunately I couldn't achieve this because OrderByDescending compares something else, but I am sending a string.
public List<DOlead> sortLead(DOuser user, string Item)
{
List<DOlead> ObjLead = new List<DOlead>();
ObjLead = _Context.leads.Where(x => x.is_converted == false).OrderByDescending(Item).ToList();
return ObjLead;
}
Kindly Help me out?
Use reflection
public List<DOlead> sortLead(DOuser user, string Item)
{
var propertyInfo = typeof(DOlead).GetProperty(Item);
List<DOlead> ObjLead = new List<DOlead>();
ObjLead = _Context.leads.Where(x => x.is_converted == false).OrderByDescending(x => propertyInfo.GetValue(x, null)).ToList();
return ObjLead;
}
Edit
After getting comment by SO, and after some research, I came across this answer and decided to modify it for user.
You have to create lambda expression first then pass it to order by clause.
Creating lambda expression.
public static class QueryableHelper
{
public static IQueryable<TModel> OrderBy<TModel>(this IQueryable<TModel> q, string name)
{
Type entityType = typeof(TModel);
PropertyInfo p = entityType.GetProperty(name);
MethodInfo m = typeof(QueryableHelper).GetMethod("OrderByProperty").MakeGenericMethod(entityType, p.PropertyType);
return(IQueryable<TModel>) m.Invoke(null, new object[] { q, p });
}
public static IQueryable<TModel> OrderByDescending<TModel>(this IQueryable<TModel> q, string name)
{
Type entityType = typeof(TModel);
PropertyInfo p = entityType.GetProperty(name);
MethodInfo m = typeof(QueryableHelper).GetMethod("OrderByPropertyDescending").MakeGenericMethod(entityType, p.PropertyType);
return (IQueryable<TModel>)m.Invoke(null, new object[] { q, p });
}
public static IQueryable<TModel> OrderByPropertyDescending<TModel, TRet>(IQueryable<TModel> q, PropertyInfo p)
{
ParameterExpression pe = Expression.Parameter(typeof(TModel));
Expression se = Expression.Convert(Expression.Property(pe, p), typeof(object));
return q.OrderByDescending(Expression.Lambda<Func<TModel, TRet>>(se, pe));
}
public static IQueryable<TModel> OrderByProperty<TModel, TRet>(IQueryable<TModel> q, PropertyInfo p)
{
ParameterExpression pe = Expression.Parameter(typeof(TModel));
Expression se = Expression.Convert(Expression.Property(pe, p), typeof(object));
return q.OrderBy(Expression.Lambda<Func<TModel, TRet>>(se, pe));
}
}
Your modified method
public List<DOlead> sortLead(DOuser user, string Item)
{
List<DOlead> ObjLead = new List<DOlead>();
ObjLead = _Context.leads.Where(x => x.is_converted == false).OrderByDescending(Item).ToList();
return ObjLead;
}
From Stack , I guess you could use reflection:
from x in db.TableName
where (x.GetType().GetProperty(stringCOLUMN_1_or2).GetValue(x, null)) == " 8"
select x;
Not sure there's any easy Linqish way to do that though...
Assuming dynamic Linq will work it would just be:
from x in objets
.Where(stringCOLUMN_1_or2 + " = ' " + 8 + "'")
select x
There is some more info about dynamic Linq with SQL here: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
You should use Expression builder to achieve this example simple with string properties:
public class OrderByData
{
public string PropertyName { get; set; }
}
public static class ExpressionBuilder
{
public static Expression<Func<T, string>> GetExpression<T>(OrderByData filter)
{
ParameterExpression param = Expression.Parameter(typeof(T), "t");
Expression exp = GetExpression<T>(param, filter);
return Expression.Lambda<Func<T, string>>(exp, param);
}
private static Expression GetExpression<T>(ParameterExpression param, OrderByData filter)
{
MemberExpression member = Expression.Property(param, filter.PropertyName);
return member;
}
}
and then call like this:
public List<DOlead> sortLead(DOuser user, string Item)
{
List<DOlead> ObjLead = new List<DOlead>();
new OrderByData { PropertyName = Item };
var deleg = ExpressionBuilder.GetExpression<lead>(filter).Compile();
ObjLead = _Context.leads.Where(x => x.is_converted == false).OrderByDescending(deleg).ToList();
return ObjLead;
}
also you can extend to use also other types not only strings.
You need to pass delegate to OrderByDescending method.
As you just have the property name so you need to access to the property dynamically, you can use dynamic expression to do so:
public List<DOlead> sortLead(DOuser user, string Item)
{
List<DOlead> ObjLead = new List<DOlead>();
ObjLead = _Context.leads.Where(x => x.is_converted == false).OrderByDescending((d) =>
Expression.Lambda(Expression.Property(Expression.Constant(d), Item)).Compile()()).ToList();
return ObjLead;
}
I have created a generic search extension method for IQueryable that enables you to search for a single property to see if a search term is contained within it.
http://jnye.co/Posts/6/c%23-generic-search-extension-method-for-iqueryable
I now want to enable the user to select multiple properties to search within each, matching if any property contains the text.
The code:
The user enters the following code to perform this search:
string searchTerm = "Essex";
context.Clubs.Search(searchTerm, club => club.Name, club => club.County)
//Note: If possible I would rather something closer to the following syntax...
context.Clubs.Search(club => new[]{ club.Name, club.County}, searchTerm);
// ... or, even better, something similar to this...
context.Clubs.Search(club => new { club.Name, club.County}, searchTerm);
This will return any golf club with 'Essex' in the Name or as the County.
public static IQueryable<TSource> Search<TSource>(this IQueryable<TSource> source, string searchTerm, params Expression<Func<TSource, string>>[] stringProperties)
{
if (String.IsNullOrEmpty(searchTerm))
{
return source;
}
// The lamda I would like to reproduce:
// source.Where(x => x.[property1].Contains(searchTerm)
// || x.[property2].Contains(searchTerm)
// || x.[property3].Contains(searchTerm)...)
//Create expression to represent x.[property1].Contains(searchTerm)
var searchTermExpression = Expression.Constant(searchTerm);
//Build parameters
var parameters = stringProperties.SelectMany(prop => prop.Parameters);
Expression orExpression = null;
//Build a contains expression for each property
foreach (var stringProperty in stringProperties)
{
var checkContainsExpression = Expression.Call(stringProperty.Body, typeof(string).GetMethod("Contains"), searchTermExpression);
if (orExpression == null)
{
orExpression = checkContainsExpression;
}
//Build or expression for each property
orExpression = Expression.OrElse(orExpression, checkContainsExpression);
}
var methodCallExpression = Expression.Call(typeof(Queryable),
"Where",
new Type[] { source.ElementType },
source.Expression,
Expression.Lambda<Func<TSource, bool>>(orExpression, parameters));
return source.Provider.CreateQuery<TSource>(methodCallExpression);
}
The error
If I change the number of parameters supplied to 1:
Expression.Lambda<Func<TSource, bool>>(orExpression, parameters.First()));
I get a new error:
UPDATE
I have written a post on the work discussed in this question. Check it out on GitHub too.
Here we go; you were pretty close - as I noted in comments, the key piece here is to use ExpressionVisitor to re-write the trees in terms of the single parameter you want to keep:
using System;
using System.Linq;
using System.Linq.Expressions;
static class Program
{
static void Main()
{
var data = new[] { new Foo { A = "x1", B = "y1", C = "y1" }, new Foo { A = "y2", B = "y2", C = "y2" },
new Foo { A = "y3", B = "y3", C = "x3" } }.AsQueryable();
var result = data.Search("x", x => x.A, x => x.B, x => x.C);
foreach (var row in result)
{
Console.WriteLine("{0}, {1}, {2}", row.A, row.B, row.C);
}
}
class Foo
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
public class SwapVisitor : ExpressionVisitor
{
private readonly Expression from, to;
public SwapVisitor(Expression from, Expression to)
{
this.from = from;
this.to = to;
}
public override Expression Visit(Expression node)
{
return node == from ? to : base.Visit(node);
}
public static Expression Swap(Expression body, Expression from, Expression to)
{
return new SwapVisitor(from, to).Visit(body);
}
}
public static IQueryable<TSource> Search<TSource>(this IQueryable<TSource> source, string searchTerm, params Expression<Func<TSource, string>>[] stringProperties)
{
if (String.IsNullOrEmpty(searchTerm))
{
return source;
}
if (stringProperties.Length == 0) return source.Where(x => false);
// The lamda I would like to reproduce:
// source.Where(x => x.[property1].Contains(searchTerm)
// || x.[property2].Contains(searchTerm)
// || x.[property3].Contains(searchTerm)...)
//Create expression to represent x.[property1].Contains(searchTerm)
var searchTermExpression = Expression.Constant(searchTerm);
var param = stringProperties[0].Parameters.Single();
Expression orExpression = null;
//Build a contains expression for each property
foreach (var stringProperty in stringProperties)
{
// re-write the property using the param we want to keep
var body = SwapVisitor.Swap(stringProperty.Body, stringProperty.Parameters.Single(), param);
var checkContainsExpression = Expression.Call(
body, typeof(string).GetMethod("Contains"), searchTermExpression);
if (orExpression == null)
{
orExpression = checkContainsExpression;
}
else
{ // compose
orExpression = Expression.OrElse(orExpression, checkContainsExpression);
}
}
var lambda = Expression.Lambda<Func<TSource, bool>>(orExpression, param);
return source.Where(lambda);
}
}
I have this sql statement
SELECT userID from users WHERE
(name='name1' AND username='username1') OR
(name='name2' AND username='username2') OR
(name='name3' AND username='username3') OR
..........
(name='nameN' AND username='usernameN')
How can I implement this statement with entity framework using LINQ?
You can use a beautiful thing called PredicateBuilder. Use it like this
var pr = PredicateBuilder.False<User>();
foreach (var name in names)
{
pr = pr.Or(x => x.Name == name && x.Username == name);
}
return query.AsExpandable().Where(pr);
Expression<Func<User, bool>> whereExpression = null;
foreach (var name in names)
{
Expression<Func<User, bool>> e1 = u => u.Name == name;
Expression<Func<User, bool>> andExpression = e1.And(u => u.Username == name);
whereExpression = whereExpression == null
? andExpression
: whereExpression.Or(andExpression);
}
return query.Where(whereExpression);
This helper may help you.
public static class ExpressionExtensions
{
public static Expression<Func<T, bool>> And<T>(
this Expression<Func<T, bool>> leftExpression,
Expression<Func<T, bool>> rightExpression)
{
if (leftExpression == null) return rightExpression;
if (rightExpression == null) return leftExpression;
var paramExpr = Expression.Parameter(typeof(T));
var exprBody = Expression.And(leftExpression.Body, rightExpression.Body);
exprBody = (BinaryExpression)new ParameterReplacer(paramExpr)
.Visit(exprBody);
return Expression.Lambda<Func<T, bool>>(exprBody, paramExpr);
}
public static Expression<Func<T, bool>> Or<T>(
this Expression<Func<T, bool>> leftExpression,
Expression<Func<T, bool>> rightExpression)
{
if (leftExpression == null) return rightExpression;
if (rightExpression == null) return leftExpression;
var paramExpr = Expression.Parameter(typeof(T));
var exprBody = Expression.Or(leftExpression.Body, rightExpression.Body);
exprBody = (BinaryExpression)new ParameterReplacer(paramExpr)
.Visit(exprBody);
return Expression.Lambda<Func<T, bool>>(exprBody, paramExpr);
}
}
and:
class ParameterReplacer : ExpressionVisitor
{
private readonly ParameterExpression _parameter;
protected override Expression VisitParameter(ParameterExpression node)
{
return base.VisitParameter(_parameter);
}
internal ParameterReplacer(ParameterExpression parameter)
{
_parameter = parameter;
}
}
NOTE: this is modified from something I have so it might not work out of the box. But it would be a good starting point.
public static IQueryable<TEntity> Where<TEntity>(
this IQueryable<TEntity> source,
IEnumerable<WhereSpecifier> orClauses) where TEntity : class
{
if (!orClauses.Any()) return source.Where(t => false);
Type type = typeof (TEntity);
ParameterExpression parameter = null;
Expression predicate = Expression.Constant(false, typeof (bool));
ParameterExpression whereEnt = Expression.Parameter(type, "WhereEnt");
foreach (WhereSpecifier orClause in orClauses)
{
Expression selector;
if (orClause.Selector != null) {
selector = orClause.Selector;
parameter = orClause.Parameter;
}
else
{
parameter = whereEnt;
Type selectorResultType;
selector = GenerateSelector<TEntity>(parameter, orClause.Column,
out selectorResultType);
}
Expression clause = selector.CallMethod(orClause.Method,
MakeConstant(selector.Type, orClause.Value), orClause.Modifiers);
predicate = Expression.Or(predicate, clause);
}
var lambda = Expression.Lambda(predicate, whereEnt);
var resultExp = Expression.Call(typeof (Queryable), "Where", new[] {type},
source.Expression, Expression.Quote(lambda));
return source.Provider.CreateQuery<TEntity>(resultExp);
}
GenerateSelector:
public static Expression GenerateSelector<TEntity>(
ParameterExpression parameter, string propertyName,
out Type resultType) where TEntity : class
{
// create the selector part, but support child properties
PropertyInfo property;
Expression propertyAccess;
if (propertyName.Contains('.'))
{
// support to be sorted on child fields.
String[] childProperties = propertyName.Split('.');
property = typeof (TEntity).GetProperty(childProperties[0]);
propertyAccess = Expression.MakeMemberAccess(parameter, property);
for (int i = 1; i < childProperties.Length; i++)
{
property = property.PropertyType.GetProperty(childProperties[i]);
propertyAccess = Expression
.MakeMemberAccess(propertyAccess, property);
}
}
else
{
property = typeof (TEntity).GetProperty(propertyName);
propertyAccess = Expression.MakeMemberAccess(parameter, property);
}
resultType = property.PropertyType;
return propertyAccess;
}
WHereSpecifier:
public class WhereSpecifier
{
public WhereSpecifier(string column, CheckMethod method, string value,
CheckMethodModifiers modifiers)
{
Modifiers = modifiers;
Value = value;
Column = column;
Method = method;
}
public WhereSpecifier(string column, CheckMethod method, string value)
: this(column, method, value, CheckMethodModifiers.None)
{
}
public Expression Selector { get; set; }
public ParameterExpression Parameter { get; set; }
public string Column { get; set; }
public CheckMethod Method { get; set; }
public CheckMethodModifiers Modifiers { get; set; }
public string Value { get; set; }
}
Usage:
var column = typeof(TEntity).Name + "ID";
var where = from id in SelectedIds
select new WhereSpecifier(column, CheckMethod.Equal, id.ToString());
return GetTable().Where(where);
I tried #Egor Pavlikhin solution but i got "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.".
According to this you can use PredicateExtensions :
var predicate = PredicateExtensions.Begin<User>();
foreach (var name in names)
{
pr = pr.Or(x => x.Name == name);
}
return _context.Users.Where(predicate);
Don't forget that entity framework also understands entity sql, so you can do this part of the query in a string. Building a string up is pretty convenient when you have dynamic stuff you need to do.
I had to construct the predicate for the 'Where' clause dynamically based on User Interface selections. 'System.Dynamic.Linq' allows to predicates from strings.
foreach (var name in names)
{
query = query.Where("Name=#0 And UserName=#1", name, name);
}
return query;
'System.Dynamic.Linq' is available as a nuget package. Check out Scott Guthrie's introduction to the topic here.
i found this way it is too simple :
var query = context.InvoiceHeader.Where( i => i.DateInvoice >= model.datedu && i.DateInvoice <= model.dateau).AsQueryable();
if(model.name != null)
{
query = query.Where(i => i.InvoiceNum.Equals(model.name));
}
if (model.status != 0 )
{
query = query.Where(i => i.REF_InvoiceStatusRecId == model.status);
}
if (model.paiements != 0)
{
query = query.Where(i => i.REF_PaymentTermRecId == model.paiements);
}
query = query.AsQueryable().OrderByDescending(x => x.RecId);
basically I want to get the values of the parameters of a called method like this:
var x = 1;
var a = 2;
var b = 3;
Do<HomeController>(o => o.Save(x, "Jimmy", a+b+5, Math.Sqrt(81)));
public static void Do<T>(Expression<Action<T>> expression) where T : Controller
{
// get the values 1,Jimmy,10,9 here
}
Well, you'd need to drill into the expression, find the MethodCallExpression, and then look at the arguments to it. Note that we don't have the value of o, so we've got to assume that the arguments to the method don't rely on that. Also we're still assuming that the lambda expression just relies on it being a MethodCallExpression?
EDIT: Okay, here's an edited version which evaluates the arguments. However, it assumes you're not really using the lambda expression parameter within the arguments (which is what the new object[1] is about - it's providing a null parameter, effectively).
using System;
using System.Linq.Expressions;
class Foo
{
public void Save(int x, string y, int z, double d)
{
}
}
class Program
{
static void Main()
{
var x = 1;
var a = 2;
var b = 3;
ShowValues<Foo>(o => o.Save(x, "Jimmy", a + b + 5, Math.Sqrt(81)));
}
static void ShowValues<T>(Expression<Action<T>> expression)
{
var call = expression.Body as MethodCallExpression;
if (call == null)
{
throw new ArgumentException("Not a method call");
}
foreach (Expression argument in call.Arguments)
{
LambdaExpression lambda = Expression.Lambda(argument,
expression.Parameters);
Delegate d = lambda.Compile();
object value = d.DynamicInvoke(new object[1]);
Console.WriteLine("Got value: {0}", value);
}
}
}
As Jon said you can check to see if the expression is a MethodCallExpression
class Program
{
static void Main(string[] args)
{
Program.Do<Controller>(c => c.Save(1, "Jimmy"));
}
public static void Do<T>(Expression<Action<T>> expression) where T : Controller
{
var body = expression.Body as MethodCallExpression;
if (body != null)
{
foreach (var argument in body.Arguments)
{
var constant = argument as ConstantExpression;
if (constant != null)
{
Console.WriteLine(constant.Value);
}
}
}
}
}
public class Controller
{
public void Save(int id, string name)
{
}
}
My universal answer is below. I hope it will help you and somebody else.
var dict = new Dictionary<string, object>();
var parameterExpressions = methodCallExpr.Arguments;
foreach (var param in method.GetParameters())
{
var parameterExpression = parameterExpressions[counter];
var paramValueAccessor = Expression.Lambda(parameterExpression);
var paramValue = paramValueAccessor.Compile().DynamicInvoke();
dict[param.Name] = paramValue;
}
Here is some code that is designed to work with any expression — in the sense that it doesn’t fundamentally assume that you are passing in a method-call expression. However, it is not complete. You will have to fill in the rest.
public static IEnumerable<object> ExtractConstants<T>(
Expression<Action<T>> expression)
{
return extractConstants(expression);
}
private static IEnumerable<object> extractConstants(Expression expression)
{
if (expression == null)
yield break;
if (expression is ConstantExpression)
yield return ((ConstantExpression) expression).Value;
else if (expression is LambdaExpression)
foreach (var constant in extractConstants(
((LambdaExpression) expression).Body))
yield return constant;
else if (expression is UnaryExpression)
foreach (var constant in extractConstants(
((UnaryExpression) expression).Operand))
yield return constant;
else if (expression is MethodCallExpression)
{
foreach (var arg in ((MethodCallExpression) expression).Arguments)
foreach (var constant in extractConstants(arg))
yield return constant;
foreach (var constant in extractConstants(
((MethodCallExpression) expression).Object))
yield return constant;
}
else
throw new NotImplementedException();
}
For the case that you have mentioned, this already works:
// Prints:
// Jimmy (System.String)
// 1 (System.Int32)
foreach (var constant in Ext.ExtractConstants<string>(
str => Console.WriteLine("Jimmy", 1)))
Console.WriteLine("{0} ({1})", constant.ToString(),
constant.GetType().FullName);
For more complex lambda expressions that employ other types of expression nodes, you will have to incrementally extend the above code. Every time you use it and it throws a NotImplementedException, here is what I do:
Open the Watch window in the debugger
Look at the expression variable and its type
Add the necessary code to handle that expression type
Over time the method will become more and more complete.
public override IQueryable<Image> FindAll(System.Linq.Expressions.Expression<Func<Image, dynamic>> Id)
{
dynamic currentType = Id.Parameters[0];
var id = currentType.Type.GUID;
var result = (_uniwOfWork as UnitOfWork).uspGetImages(id.ToString());
return FindAll();
}
use keyword dynamic.