0

We wanna create the following code dynamically with reflection:

TestDatabaseEntities entities = new TestDatabaseEntities();
entities.Database.Log = s => System.Diagnostics.Debug.WriteLine(s); // to show generated tsql
List<Employee> employees = entities.Employees.Where(c => SqlFunctions.StringConvert((double?)c.SomeNumber).Trim().Contains("123")).ToList();

Above code works great. now we wanna create it with reflection dynamically.
We done it as follows :

Type entityType = typeof(TEntity);
ParameterExpression parameterExpression = Expression.Parameter(entityType, "entity");

Type nullableDoubleType = typeof (double?);
//leftSile == {entity.SomeNumber}, it's OK
UnaryExpression unaryExpression  = Expression.Convert(leftSile, nullableDoubleType);
MethodInfo stringConvertMethodInfo = typeof(SqlFunctions).GetMethod("StringConvert", new[] { nullableDoubleType });
MethodInfo trimMethodInfo = typeof(string).GetMethod("Trim", new Type[] {});
ConstantExpression newRightSide = Expression.Constant(valueObject.ToString());

var traceVariable1 = Expression.Call(stringConvertMethodInfo, unaryExpression);
var traceVariable2 = Expression.Call(traceVariable1, trimMethodInfo);
Expression resultExpression = Expression.Call(traceVariable2, methodInfo, newRightSide);
Expression<Func<Employee, bool>> expression = Expression.Lambda<Func<TEntity, bool>>(resultExpression, parameterExpression);

// expression == {entity => (StringConvert(Convert(entity.SomeNumber)).Trim().Contains("123"))}

The expression created successfully, but when we use it within EntityFramework it throws an exception:

List<Employee> employees2 = entities.Employees.Where(expression.Compile()).ToList();
//Exception :
//An unhandled exception of type 'System.NullReferenceException' occurred in System.Core.dll
//Additional information: Object reference not set to an instance of an object.

StackTrace:

   at lambda_method(Closure , Employee )
   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at ConsoleApplication2.Program.Main(String[] args) in d:\Works\ConsoleApplication2\ConsoleApplication2\Program.cs:line 36
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
Mohammad Dayyan
  • 21,578
  • 41
  • 164
  • 232
  • See duplicate. Add breakpoints, start debugging. It can be as simple as `c` being null where you dereference `c.SomeNumber`. – CodeCaster Dec 16 '14 at 12:40
  • Could you please post some duplicate links? – Mohammad Dayyan Dec 16 '14 at 12:42
  • It's on top of your question, [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it). – CodeCaster Dec 16 '14 at 12:43
  • @CodeCaster I saw the link, It's completely different with my question. I wanted to create `Expression` with `SqlFunctions.StringConvert`. But the link is something else !!! – Mohammad Dayyan Dec 16 '14 at 12:48
  • All NullReferenceExceptions are the same. That link gives you hints for the debugging, which we can't do. The exception is thrown in `Where(expression.Compile())` (called through `.ToList()`) as you can see from the stack trace. Place breakpoints and inspect your variables until you see the `null` that throws. – CodeCaster Dec 16 '14 at 12:49

0 Answers0