Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

OrderBy null reference error.

$
0
0

Hi, I'm new in all of this about LinQ and Entity Framework.

Here is the code:

public class MyClass
{
public int MyClassId{get;set;}
public string Description{get;set;}

public virtual iList<ChildClass> Childs {get;set;}
}
public class ChildClass
{
public int ChildClassId {get;set;}
public string Description {get;set;}

public int MyClassId {get;set;}
public virtual MyClass MyClass {get;set;}
}
....
IQueryable<MyClass> col= from m in context.MyClass
select m;
if (condition)
{
col = col.Include(i=>i.Childs);
}
//PropertyName is an string argument of the method
var propertyInfo = new MyClass().GetType().GetProperty("PropertyName");
if (!(propertyInfo == null))
{
if (orderDesc)
{
col= col.OrderByDescending(p => propertyInfo.GetValue(p));
}
else
{
col = col.OrderBy(p => propertyInfo.GetValue(p));
}
}
return await col.ToListAsync();

The problem is when the condition in the first if clause is true and add the .include childs to col, and then try to applies the orderby y get the following error:

Nombre Valor Tipo
$exception Count = 1 System.AggregateException
▶ Data {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
HResult -2146233088 int
HelpLink null string
▶ InnerException {"Object reference not set to an instance of an object."} System.Exception {System.NullReferenceException}
▶ InnerExceptions Count = 1 System.Collections.ObjectModel.ReadOnlyCollection<System.Exception>
Message"One or more errors occurred. (Object reference not set to an instance of an object.)" string
Source"System.Private.CoreLib" string
StackTrace" at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)\r\n at (......)XXXController.cs:line 41\r\n at lambda_method(Closure , Object , Object[] )\r\n at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)\r\n at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()" string
▶ TargetSite {TResult GetResultCore(Boolean)} System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}
▶ Static members
▶ Non-Public members

If I Comment the first if clause (where adds the childs) its works and retrieve me the collection with no error.  Also I noticed that if I change

p => propertyInfo.GetValue(p)

with for example

p => p.Description

works fine wihout comment the include.

Any suggestion?

Thanks!smile


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>