Linq Expression Could Not Be Translated - DistinctBy Breaking Linq [duplicate] - c#

In my .NET 6,0 app I'm trying to use (new to .NET 6.0 https://learn.microsoft.com/en-us/dotnet/api/system.linq.queryable.distinctby?view=net-6.0) method DistinctBy, something like this:
return context.Table
.Where(x => x.IsLive)
.DistinctBy(x => x.Field1)
.ToList();
Buld is fine, no errors, but at runtime I get this:
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[MyType] DistinctBy[DbFundHistoPrice,String](System.Linq.IQueryable`1[VanEck.Repositories.Entities.Website.Funds.DbFundHistoPrice], System.Linq.Expressions.Expression`1[System.Func`2[VanEck.Repositories.Entities.Website.Funds.DbFundHistoPrice,System.String]])' method, and this method cannot be translated into a store expression.
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.DefaultTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.Convert()
at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass41_0.<GetResults>b__1()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass41_0.<GetResults>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__31_0()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
*my call here*
Other queries without new .NET 6 methods work fine (upgrading from 5 so there are some).
What am I missing here? Somethig in startup or in project settings?
I know that these extensions can be trimmed during build but I see no reason for that here since the method is actually used.

It seems you are using older ORM (EF 6?) which does not support this method.
DistinctBy is not supported even by EF Core (which I recommend upgrading to) at the moment. See this issue - Translate LINQ DistinctBy. You can try rewriting it with GroupBy(e => e.Field1).Select(g => g.First()).
See also:
Support new .NET LINQ features issue

Related

How to modify expression-based filters to avoid client-side evaluation in Entity Framework Core 3.0

I have the following code that used to convert Func-based filters to Expression and filter the data in Entity Framework Core 2.2:
public async Task<TType> GetDataAsync<TType>(Func<TType, bool> filtering = null) where TType : class
{
Expression<Func<TType, bool>> filteringExpression = (type) => filtering(type);
if (filtering != null)
//return await myContext.Set<TType>().FirstOrDefaultAsync(filteringExpression);
return await myContext.Set<TType>().Where(filteringExpression ).FirstOrDefaultAsync();
return await myContext.Set<TType>().FirstOrDefaultAsync();
}
This is how I use it:
public async Task<DataLog> GetDataLogByID(Guid dataLogID) => await GetDataAsync<DataLog>(dataLog => dataLog.ID == dataLogID);
(Un)fortunately, when I upgraded to Entity Framework Core 3.0, the code threw an InvalidOperationException as the expression can't be turned into SQL query (although it filters only a property that matches a database column):
System.InvalidOperationException: 'The LINQ expression
'Where(
source: DbSet,
predicate: (f) => Invoke(__filtering_0, f[DataLog]) )' could not be translated. Either rewrite the query in a form that can be
translated, or switch to client evaluation explicitly by inserting a
call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or
ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for
more information.
So can you tell me, how I should modify the code to make sure that all (most) of the processing stay on the server side? What is the best practice to keep the generic code yet comply with the standards?
Congratulations, you've discovered one of the breaking changes in EF Core 3.0 - LINQ queries are no longer evaluated on the client
Old behavior
Before 3.0, when EF Core couldn't convert an expression that was part of a query to either SQL or a parameter, it automatically evaluated the expression on the client. By default, client evaluation of potentially expensive expressions only triggered a warning.
New behavior
Starting with 3.0, EF Core only allows expressions in the top-level projection (the last Select() call in the query) to be evaluated on the client. When expressions in any other part of the query can't be converted to either SQL or a parameter, an exception is thrown.
See the docs (link above) for more info, but the warnings you experienced before upgrading are now generating InvalidOperationExceptions and has nothing to do with SQLite, you'd get the same issues with SQL Server.
Only way around this is to ensure that your filtering expression/func can be converted to appropriate SQL... or revert to EF Core < 3.0
UPDATE
You could try not wrapping the passed Func and change the parameter type to Expression<Func<TType, bool>> (it shouldn't require any changes to code calling the method)
public async Task<TType> GetDataAsync<TType>(Expression<Func<TType, bool>> filter = null)
where TType : class
{
var query = myContext.Set<TType>();
if (filter != null)
query = query.Where(filter);
return await query.FirstOrDefaultAsync();
}
Just noticed that the call to GetDataAsync appears to be incorrect and has an extra type parameter Guid which should be removed from this example.
public async Task<DataLog> GetDataLogByID(Guid dataLogID) =>
await GetDataAsync<DataLog>(dataLog => dataLog.ID == dataLogID);

NullReferenceException in EF Core when using StringComparison overload for predicates

We are converting a project from using EF to using EF Core. We have the following line of code which used to work but now does not:
// throws NullReferenceException
var u = db.Users.FirstOrDefault(x => x.PresenterID.Equals(uid, StringComparison.OrdinalIgnoreCase));
However, if we don't use the StringComparison overload, it works:
// this works
var u = db.Users.FirstOrDefault(x => x.PresenterID.Equals(uid));
This is a large project and we would like to avoid finding and modifying all code that does such comparisons. Why does this throw a NullReferencException and can it be avoided without changing our code? Here is the stack trace. Thanks.
at lambda_method(Closure , User ) at
System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext() at
System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source)
at
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable1.GetEnumerator()
at
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__172.MoveNext()
at
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext()
at System.Linq.Enumerable.First[TSource](IEnumerable1 source) at
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.b__0(QueryContext
qc) at
Our.Project.Service.ContractsFolderService.ValidateContractUsers(BIContract
xmlContract, IDataContext db) in
C:\Projects\Out.Project\Main\Service\ContractsFolderService.cs:line
436
According to this open issue on the EntityFrameworkCore Github repo, that overload is not yet supported with LINQ to SQL. See this specific comment which gives some detail on the problem preventing this overload from being translated: https://github.com/aspnet/EntityFrameworkCore/issues/1222#issuecomment-443116169
I'm guessing that the null reference exception is occurring because its pulling back all the results to evaluate your string comparison on the client side, and for one or more of those results PresenterID is null.

Linq Errors on ToList(), Any(), Count(), Sum()

I am getting the following errors, they are all related to system.linq. The strange thing is that the method seems to work sometimes, the errors are not happening consistently.
Count() Code:
using (var dbContext = new Entities(GlobalStuff.EntityConnection))
{
heartBeat.NumSlipsInSecurityUploadQueue = dbContext.SecurityUploadQueues.Count();
heartBeat.NumSlipsInDataStreamQueue = dbContext.DataStreamQueues.Count();
}
SecurityUploadQueues Property:
Public ReadOnly Property SecurityUploadQueues() As ObjectSet(Of SecurityUploadQueue)
Get
If (_SecurityUploadQueues Is Nothing) Then
_SecurityUploadQueues = MyBase.CreateObjectSet(Of SecurityUploadQueue)("SecurityUploadQueues")
End If
Return _SecurityUploadQueues
End Get
End Property
Private _SecurityUploadQueues As ObjectSet(Of SecurityUploadQueue)
The SecurityUploadQueue property is an EntityObject
Count() Error:
Error Uploading HeartBeat System.InvalidOperationException: Sequence contains more than one element
at System.Linq.Enumerable.Single[TSource](IEnumerable1 source)
at System.Data.Objects.ELinq.ObjectQueryProvider.<>c__111.b__11_3(IEnumerable1 sequence)
at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1 query, Expression queryRoot)
at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
at SettlerService.SettlerService.UploadHeartBeat()
Any() Code:
var dataToUpload = (from bet in dbContext.DataStreamQueues select bet).Take(200);
if (dataToUpload.Any())
Any() Error:
System.InvalidOperationException: The specified cast from a
materialized 'System.Int32' type to the 'System.Boolean' type is not
valid. at
System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader1.GetValue(DbDataReader
reader, Int32 ordinal) at lambda_method(Closure , Shaper ) at
System.Data.Common.Internal.Materialization.Coordinator1.ReadNextElement(Shaper
shaper) at
System.Data.Common.Internal.Materialization.Shaper1.SimpleEnumerator.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable1 source) at
System.Data.Objects.ELinq.ObjectQueryProvider.<>c__111.<GetElementFunction>b__11_3(IEnumerable1
sequence) at
System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1
query, Expression queryRoot)
at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.Any[TSource](IQueryable1 source)
at SettlerService.SettlerService.UploadDataStream()
I've done some googling and can't find much on this issue. I thought it might be related to the version of the system.core library (which system.linq is part of) but couldn't see an issue. I am using .Net 4.7.2
The second error implies that there is one columns in your DataStreamQueues database table with type of Int32 but the type of the equivalent property in DataStreamQueues entity is bool; so check if all columns and properties types match.
Regarding the first exception, it's a bit strange! because this exception suggests that somewhere in your code you are calling Single() method on a set that has multiple items and as Single() expects only one item, it throws an exception, however I don't see any calls to Single() in the provided code.

LINQ to SQL: intermittent AccessViolationException wrapped in TargetInvocationException

Since a few weeks we are experiencing W3WP-crashes with our ASP.Net web application. These started after our webservers were updated. Our application did not change and has been stable for years.
Our situation seems to be a lot like this earlier question. And this question might also be related, though in our case the queries run fine in 99.9% of the times used.
We use a lot of uncompiled LINQ queries and tried if compiling them would prevent these crashes. The number of crashes decreased drastically, but they still do occur.
Also wrapping our queries in a try catch and then catching the TargetInvocationException does not work. The exception is not caught.
When a crash happens, we get a WER-report and can retreive a crash dump.
A stack trace from a dump for an uncompiled query typically looks like this:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Data.Linq.SqlClient.QueryConverter.VisitInvocation(InvocationExpression invoke)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.VisitExpression(Expression exp)
at System.Data.Linq.SqlClient.QueryConverter.VisitBinary(BinaryExpression b)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.VisitExpression(Expression exp)
at System.Data.Linq.SqlClient.QueryConverter.VisitBinary(BinaryExpression b)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.Visit(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.VisitWhere(Expression sequence, LambdaExpression predicate)
at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.VisitWhere(Expression sequence, LambdaExpression predicate)
at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.VisitSelect(Expression sequence, LambdaExpression selector)
at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.VisitDistinct(Expression sequence)
at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.ConvertOuter(Expression node)
at System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query, SqlNodeAnnotations annotations)
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataQuery'1.System.Collections.Generic.IEnumerable.GetEnumerator()
at System.Linq.Buffer'1..ctor(IEnumerable'1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable'1 source)
The stack trace from a dump for a compiled query looks like:
at System.RuntimeMethodHandle.InvokeMethod(System.Object, System.Object[], System.Signature, Boolean)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(System.Object, System.Object[], System.Object[])
at System.Delegate.DynamicInvokeImpl(System.Object[])
at System.Data.Linq.SqlClient.SqlProvider.AssignParameters(System.Data.Common.DbCommand, System.Collections.ObjectModel.ReadOnlyCollection`1, System.Object[], System.Object)
at System.Data.Linq.SqlClient.SqlProvider.Execute(System.Linq.Expressions.Expression, QueryInfo, System.Data.Linq.SqlClient.IObjectReaderFactory, System.Object[], System.Object[], System.Data.Linq.SqlClient.ICompiledSubQuery[], System.Object)
at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(System.Linq.Expressions.Expression, QueryInfo[], System.Data.Linq.SqlClient.IObjectReaderFactory, System.Object[], System.Data.Linq.SqlClient.ICompiledSubQuery[])
at System.Data.Linq.SqlClient.SqlProvider+CompiledQuery.Execute(System.Data.Linq.Provider.IProvider, System.Object[])
at System.Data.Linq.CompiledQuery.ExecuteQuery(System.Data.Linq.DataContext, System.Object[])
Does anyone know what might have changed the behavior our application? We know it was "an update" (but not exactly which one), but we are more interested in it's technical background.
Of course, we would also welcome a solution to prevent our application from crashing.
I thought I would post a solution, that we found to this issue, because we started experiencing the problem recently.
We have many servers that run our code just fine but only 1 was crashing a couple of times a week with this error. I believe this server was on .net 4.5.2.
We opened a ticket with Microsoft since the unhandled exception was happening in their stack.
They looked at our dump and came back with this solution which worked.
A new fix is available at
https://support.microsoft.com/en-us/kb/3139544
It would be better if you move to .net 4.6.1
I hope this solution will help anyone else that finds themselves reading this.
Hard to tell without seeing any of your Linq Code but I would venture a wild guess that an it's an internal (casting) error with the linq library you are using.
As you mentioned that you upgraded recently
(which .NET version did you upgrade from and to ?)
I had similar issue which was resolved by installing windows updates, which you say you have done with some resulting success?
Try to identify the user inputs that cause error. Try to handle the casting yourself rather than relying on Linq

Telerik MVC grid - ArgugumentException when filtering

Greetings,
I'm having the problem posted here (the post dated August 18th is mine), but not getting anywhere.
In a nutshell, filtering with Telerik's MVC grid causes an ArgumentException with the message "The argument to DbIsNullExpression must refer to a primitive or reference type." Interestingly, if you .ToList() the IQueryable first, you avoid the problem (but pulling back all that data isn't a good solution). Also using Entity Framework and Ajax, not sure if that's an issue or not. Here's the stack trace:
System.ArgumentException was unhandled by user code
Message=The argument to DbIsNullExpression must refer to a primitive or reference type.
Source=System.Data.Entity
StackTrace:
at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.ValidateIsNull(DbExpression argument, Boolean allowRowType)
at System.Data.Objects.ELinq.ExpressionConverter.EqualsTranslator.CreateIsNullExpression(ExpressionConverter parent, Expression input)
at System.Data.Objects.ELinq.ExpressionConverter.EqualsTranslator.TypedTranslate(ExpressionConverter parent, BinaryExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.NotTranslator.TypedTranslate(ExpressionConverter parent, UnaryExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.NotEqualsTranslator.TypedTranslate(ExpressionConverter parent, BinaryExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.ConditionalTranslator.TypedTranslate(ExpressionConverter parent, ConditionalExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.BinaryTranslator.TypedTranslate(ExpressionConverter parent, BinaryExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateIntoCanonicalFunction(String functionName, Expression Expression, Expression[] linqArguments)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.CanonicalFunctionDefaultTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.EqualsTranslator.TypedTranslate(ExpressionConverter parent, BinaryExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input, DbExpressionBinding& binding)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression& source, DbExpressionBinding& sourceBinding, DbExpression& lambda)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.AggregateTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.Convert()
at System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()
at System.Data.Objects.ObjectQuery`1.GetEnumeratorInternal()
at System.Data.Objects.ObjectQuery.System.Collections.IEnumerable.GetEnumerator()
at System.Linq.Enumerable.d__b1`1.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at System.Data.Objects.ELinq.ObjectQueryProvider.b__3[TResult](IEnumerable`1 sequence)
at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression)
at Telerik.Web.Mvc.Extensions.QueryableExtensions.Count(IQueryable source) in C:\Projects\SoftExposure\Telerik.Web.Mvc\Extensions\QueryableExtensions.cs:line 399
at Telerik.Web.Mvc.Extensions.QueryableExtensions.ToGridModel(IQueryable queryable, Int32 page, Int32 pageSize, IList`1 sortDescriptors, IEnumerable`1 filterDescriptors, IEnumerable`1 groupDescriptors) in C:\Projects\SoftExposure\Telerik.Web.Mvc\Extensions\QueryableExtensions.cs:line 45
at Telerik.Web.Mvc.UI.GridDataProcessor.EnsureDataSourceIsProcessed() in C:\Projects\SoftExposure\Telerik.Web.Mvc\UI\Grid\GridDataProcessor.cs:line 162
at Telerik.Web.Mvc.UI.GridDataProcessor.get_ProcessedDataSource() in C:\Projects\SoftExposure\Telerik.Web.Mvc\UI\Grid\GridDataProcessor.cs:line 132
at Telerik.Web.Mvc.GridActionAttribute.OnActionExecuted(ActionExecutedContext filterContext) in C:\Projects\SoftExposure\Telerik.Web.Mvc\UI\Grid\GridActionAttribute.cs:line 104
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.c__DisplayClassd.c__DisplayClassf.b__c()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException:
and here's the code that causes it
// Note: We need to use a ViewModel rather than the entity directly because the entity relationships
// will cause a circular reference when used via Ajax.
// See http://www.telerik.com/help/aspnet-mvc/telerik-ui-components-grid-troubleshooting.html#ServerError
//
private IEnumerable GetCustomers()
{
var model = new NorthwindEntities().Customers
.Select(c => new CustomerModel()
{
CustomerID = c.CustomerID,
CompanyName = c.CompanyName,
ContactName = c.ContactName
}); // Call .ToList() here to avoid "The argument to DbIsNullExpression must refer to a primitive or reference type."
// when filtering.
// See http://www.telerik.com/community/forums/aspnet-mvc/grid/the-argument-to-dbisnullexpression-must-refer-to-a-primitive-or-reference-type.aspx
return model;
}
Stepping through the source, it's easy to see that it's happening in the QueryableExtensions.Count() method, but the real reason is because of what's happening in the .Where() method when one has filterDescriptors. Whatever the expression building stuff is doing seems to be the cause.
This is the first time I've looked that deeply into expression trees and what not, if anyone can suggest something to try, it's appreciated.
Regards,
Mike
Looking over the thread it seems as if Telerik was not able to reproduce the issue on their end, nor were they able to get a sample project displaying the issue. Did you attempt to package this and send it over to them via their support ticketing system (different than their online forums). I'm sure they'd appreciate getting a hold of something reproducing the issue and you should be able to get a resolution from their support team :)
Telerik was kind enough to open a support ticket (I'm using the free, open source version). Turns out the issue is resolved in the latest drop - 2010.2.825.

Categories