FAQ Database Discussion Community


How to use Expression Tree to safely access path of nullable objects?

c#,lambda,path,tree,expression-trees
When I get deserialized XML result into xsd-generated tree of objects and want to use some deep object inside that tree a.b.c.d.e.f, it will give me exception if any node on that query path is missing. if(a.b.c.d.e.f != null) Console.Write("ok"); I want to avoid checking for null for each level...

Expression tree yields Argument exception

c#,linq,expression-trees
I have the following piece of code, all works well until I get to the very last line where it fails with the following exception: Method 'Boolean Contains(System.Linq.Expressions.ConstantExpression)' declared on type 'System.Collections.Generic.List`1[System.Linq.Expressions.ConstantExpression]' cannot be called with instance of type 'System.Guid' var filter = new List<SomeObj> { new SomeObj { Id...

NHibernate, expression trees, and eliminating repetition

c#,linq,nhibernate,linq-to-sql,expression-trees
We have implemented a security layer around our NHibernate persistence layer in a way that hopes to prevent a user from even receiving an object back from the database if he shouldn't have access to it. That security layer looks like this: public static IQueryable<T> Secure<T>(this Queryable<T> query){ //if T...

Fastest way to memoize expression

c#,.net,expression,expression-trees,memoization
I have a function, that transform input Expression to output BlockExpression. So I write this code: private static readonly Dictionary<Expression, BlockExpression> MemberMemoizeDictionary = new Dictionary<Expression, BlockExpression>(); private static BlockExpression CreateBody<TProperty>(CustomComparer<T> comparer, Expression<Func<T, TProperty>> member, bool createLabel) where TProperty : IComparable<TProperty>, IComparable { BlockExpression expression; if...

Providing a generic key comparison based on a collection of a generic type

c#,linq,generics,expression-trees,func
I have created my own InsertOrUpdate() implementations for a few types like this: public IEnumerable<Genre> InsertOrUpdate(IEnumerable<Genre> genres) { foreach (var genre in genres) { var existingGenre = _context.Genres.SingleOrDefault(x => x.TmdbId == genre.TmdbId); if (existingGenre != null) { existingGenre.Update(genre); yield return existingGenre; } else { _context.Genres.Add(genre); yield return genre; } }...

Convert an Expression> to an Expression> so that T is a member of T1

c#,lambda,expression-trees
We have an entity of type T1 which has a member of type T. something like this : public class T1 { public T Member{get;set;} } User can use our UI to give us a filter over T and we have translate it to an expression of a function that...

How to get the where clause from IQueryable defined as interface

c#,linq,entity-framework,lambda,expression-trees
class Program { static void Main(string[] args) { var c = new SampleClass<ClassString>(); c.ClassStrings.Add(new ClassString{ Name1 = "1", Name2 = "1"}); c.ClassStrings.Add(new ClassString{ Name1 = "2", Name2 = "2"}); var result = c.Query<ClassString>().Where(s => s.Name1.Equals("2")); Console.WriteLine(result); Console.ReadLine(); } } public class ClassString { public string Name1 { get; set;...

Where clause not working with parantheses

nhibernate,fluent-nhibernate,expression-trees,nhibernate-queryover
Suppose the following Query using a NH 3.4 and RepositoryPattern var list = _repository .QueryOver() .Where(x => (x.Age > 20)) // notice the parantheses .Future() .ToList(); Whith these parantheses added the NH is failing to work, and causes a SO exception. If replacing .Where(x => (x.Age > 20)) with .Where(x...

Invoke multiple Expressions with .NET 3.5

c#,performance,lambda,expression-trees
Alternative solution Although I was (and for this project still am) limited to .NET 3.5, I have had success using the DLR version of Expression Trees. Which is released under the Apache License version 2.0. This added support for all (maybe a few more or less, but probably not) .NET...

Expression Lambda with types known at runtime

c#,lambda,expression-trees
I am trying to make some Expressions where I will be using a lambda to create two methods: a selector and condition. Simplified the usage is condition(selector(data)), but the intemediate type is only known at runtime. I have the following code which works as long as the intemediate type is...

How to access OrderBy clause from MethodCallExpression

c#,linq,expression,expression-trees
I have a custom LINQ provider that processes a MethodCallExpression that has a OrderBy clause inside it. How can I get hold of the OrderBy clause so that I may process it?

C# Expressions - FatalExecutionEngineError

c#,debugging,visual-studio-2013,expression,expression-trees
Today I was debugging some code of mine that builds a few ExpressionTrees, compiles them to callable Delegates and calls them afterwards if required. While doing this I encountered a FatalExecutionEngineError stepping through the code: At first I was a little bit shocked since I had no idea what could...

Is a generic object builder possible in C#?

c#,generics,expression-trees,builder
I'm writing some unit tests for a reporting system that uses some pretty complex composition of DTOs. To test the system I find myself writing a lot of code like this: var items = new List<Item> { new Item { Things = new List<Thing> { new Thing { Stuff =...

ArgumentException calling Expression.IfThenElse

vb.net,linq,expression-trees
I'm trying to build this LINQ query: Result = Result.Where(Function(Row) If(IsDBNull(Row(7)), False, Convert.ToInt32(Row(7)) > 10)) Result is a IEnumerable(Of Object()). I manage to build the expression with this code, but at the last line, I get an error message. The code I have is this: Dim whereMethod = GetType(Queryable).GetMethods(BindingFlags.Public Or...

How to use expressions to sort a collection based on an inherited interface property

c#,expression-trees
This problem has been discussed to an extent in this question: Create Generic Expression from string property name but perhaps I'm missing the answer, or it is subtly different. I have the following queryable extension method: public static IQueryable<TSource> OrderByPropertyDescending<TSource>(IQueryable<TSource> source, string propertyName) { var sourceType = typeof (TSource); var...

Use Expression tree to implement interface by proxying existing implementation

c#,expression-trees
Say I have the following interface and two implementations. public interface IPerson { string Talk(); void Lunch(); } public class DutchPerson : IPerson { public string Talk() { return "Ik spreek Nederlands."; } public void Lunch() { EatBroodjeKroket(); } private void EatBroodjeKroket() { } } public class EnglishPerson : IPerson...

Assigning a value to a property by reference to a lambda expression

c#,entity-framework,lambda,expression-trees
I have 2 objects (a DTO and a Entry Framework Object) and I want to update the EF Entity if the corresponding value in the DTO is different. I envisage it would be done like this: UpdateIfDifferent(dtoObject, x => x.MailStatus, efObject, r => r.MailStatus); UpdateIfDifferent(dtoObject, x => x.WebStatus, efObject, r...

How to get a property name of a given type strongly typed?

c#,.net,reflection,expression-trees
I would like to be able to retrieve the name of a property of a type using a strongly typed syntax. I already got a function to get a property name of an instance: public static string PropertyName<T, TReturn>(this T obj, Expression<Func<T, TReturn>> property) where T : class { MemberExpression...

call First LINQ method

vb.net,linq,expression-trees
I have this: Dim aggregator_func As MethodInfo = Nothing aggregator_func = GetType(Enumerable).GetMethods(BindingFlags.Public Or BindingFlags.Static). Where(Function(m) m.Name = "First").Where(Function(m) m.ReturnType.FullName = "")(0).MakeGenericMethod(GetType(Object)) Dim groupparameter = Expression.Parameter(GetType(Linq.IGrouping(Of Object(), Object())), "g") Dim aggregation As Expression I would like to call this: g.First()(0) g.First returns an object array, but I need only the object...

Would this be the correct usage of an expression tree?

c#,expression-trees
I've these two similar methods and I feel they can be replaced with an expression tree passing in the greater than or less than signs public List<IAccount> IsGreater(DateTime someDate) { return AccountList.Where(a => a.AccountDate >= someDate && a.SomeBoolMethod() && a.SomeOtherBoolMethod()) } public List<IAccount> IsLess(DateTime someDate) { return AccountList.Where(a => a.AccountDate...

Use the same lambda parameter across multiple filters

c#,linq,entity-framework,parameter-passing,expression-trees
I am writing a class that allows users to search for entities based on a search term, working against Entity Framework under the hood. Every searchable field is registered with the class. For string fields, the search simply calls String.Contains. For look-up values, a call out to the database lookup...

Dynamic where clause to filter collection elements

c#,linq,expression-trees
I have a collection List<List<object>>, which I need to filter out based on wheater the List<object> collection contains given element. I was able to build the where clause, but i get the following Exception: An exception of type 'System.InvalidOperationException' occurred in System.Core.dll but was not handled in user code Additional...

Check for Null in an Expression

c#,lambda,expression-trees
I have an Expression that looks like this: obj => obj.Child.Name where Name is a string. What I want to do is get the value of Name. I can get it just fine by compiling the method and invoking it, however a NullReferenceException is thrown if Child is null. Is...

Replace part of BlockExpression

c#,.net,expression,expression-trees
Here is a BlockExpression var compareTo = GetCompareToExpression<TProperty>(expression, parameters); var compareToVariable = compareTo.Key; var compareToCall = compareTo.Value; var zero = Expression.Constant(0, typeof (int)); LabelTarget ret = Expression.Label(typeof (int)); var block = Expression.Block(new[] {compareToVariable}, Expression.Assign(compareToVariable, compareToCall), Expression.IfThen(Expression.NotEqual(compareToVariable, zero), Expression.Return(ret, compareToVariable)), Expression.Label(ret, zero)); return block;...

Combine property selector expression tree and value to create a predicate for EF filtering - create filter from lambda selector and value

c#,linq,entity-framework,lambda,expression-trees
Given a simple class with arbitrary properties (for discussion lets say Id, Name, and Description) and given an instance of that class, I want to find matching entries in the database by specifying the property to match I'm trying to do something in this respect similar to the AddOrUpdate method...

OrderBy with SwitchExpression in Linq to entities

c#,linq,linq-to-entities,expression,expression-trees
I need make custom orderby for enum. I try use SwitchExpression: public static IQueryable<T> MyOrderByEnum<T>(this IQueryable<T> source, string propName, Type enumType) { var type = typeof (T); var property = type.GetProperty(propName); var parameter = Expression.Parameter(type, "p"); var propertyAccess = Expression.Property(parameter, property); var enumValues = Enum.GetValues(enumType); var switchCases = new SwitchCase[enumValues.Length];...

Create expression for a simple math formula

c#,.net,expression,.net-4.5,expression-trees
I have some fun with Expressions and a question appears: it throws an exception that I didn't suppose. I have an input - simple math formula, for example 2*x+3, and I want to create an expression tree for it. So I write this code using System; using System.Linq.Expressions; namespace ConsoleApplication50...

Apply a dynamically created lambda to an object instance

c#,lambda,expression,expression-trees
I have some code which dynamically create a lambda starting from strings. For example, I have a filter class like the following: public class Criteria { public string Property { get; set; } public string Operator { get; set; } public string Value { get; set; } } And I...

How to call a lambda using LINQ expression trees in C# / .NET

c#,.net,linq,lambda,expression-trees
I want to use expression trees to dynamically create a method to call a lambda. The following code runs fine for the first call to the ComposeLambda function, but the second call fails with the following error message. Incorrect number of arguments supplied for call to method 'Int32 lambda_method(System.Runtime.CompilerServices.Closure, Int32)'...

How to get Expression for Nullable values ( fields ) without converting from Expression.Convert in C#?

c#,lambda,expression-trees,linq-expressions
I am dealing with the scanario of Nullable types during formation of dynamic query expressions. These expressions would fetch filtered data from any SQL Tables( interfacing with Code First classes using EF ). I have normal object ( e.g Consignment operating on several properties along with Nullable properties). My expression...

Expression Trees with dynamic parameter

c#,.net,c#-4.0,dynamic,expression-trees
I want to convert this: Func<dynamic, object> myFunc = t => return t.Name + " " + t.Surname; Into an Expression Tree. What I have came up with, is this: ParameterExpression target = ExpressionParameter(typeof(dynamic), "target"); ParameterExpression result = ExpressionParameter(typeof(object), "result"); BlockExpression block = Expression.Block( new [] { result }, Expression.Assign(...

Possible to wrap Expression<> and Func<> after Func defined?

c#,expression-trees
I create two kinds of nearly identical mapping functions in my View Models to map from POCOs, one for Queryables and one for Collections. Is it possible to create one method that does both so I can remove the duplicate code? I'd like to only keep the Expression<Func<>> then use...

call sum in expression tree

vb.net,linq,sum,expression-trees
I have this query: Dim test = result.GroupBy(Function(row) groupedindexes.Select( Function(grpindex) row(grpindex)).ToArray, comp). Select(Function(g) New groupedresult(g.Key, g.Sum(Function(x) Convert.ToInt32(x(3))))) At the moment, I'm building this: g.Sum(Function(x) Convert.ToInt32(x(3))) I have this so far: Dim groupparameter = Expression.Parameter(GetType(Linq.IGrouping(Of Object(), Object())), "g") Dim objectparameter = Expression.Parameter(GetType(Object()), "x") convertMethod = GetType(System.Convert).GetMethod("ToInt32", New...

How to remove Parantheses from System.Linq.Expressions.Expression?

c#,linq,lambda,expression,expression-trees
Suppose the following class defined: public class Person { public int Age { get; set; } } Now I want to build an Expression which compares the Age property to be Greather than 20, like this: ParameterExpression param = Expression.Parameter(typeof(Person), "Person"); MemberExpression member = Expression.Property(param, "Age"); ConstantExpression constant = Expression.Constant(20);...

call ToArray on LINQ select query

vb.net,linq,expression-trees,toarray
I have this query: Dim test = result.GroupBy(Function(row) groupedindexes.Select( Function(grpindex) row(grpindex)).ToArray, comp) I'm building an expression tree. I have already build the part inside the GroupBy function and now I would like to call the ToArray method. Here is the code: Public Function Grouping(ByVal result As IEnumerable(Of Object()), ByVal groupedindexes...

Using Expressions to combine Funcs with different signature

c#,expression-trees
I am using the following class to wrap some DocumentDB access which allows me to store multiple entities in the same collection: public class TypedEntity<T> { public string Type { get; set; } public T Item { get; set; } public TypedEntity(T item) { Id = Guid.NewGuid().ToString(); Item = item;...