SQLNullValueException: Data is null. this method or property cannot be called on null values when using ToListAsync from EntityFramework Core

Viewed 123

I am using entity framework core 2, i just updated my model to have 3 new fields. I have set all 3 properties to be nullable:

public int? FACategoryID { get; set; }
public int? Department { get; set; }
public int? CostCenter { get; set; }

In the database, the columns are also nullable:

enter image description here

However when I attempt to convert a IQueryable collection of these models to a list. Like this:

crnList = GetCRNList(true, userLabs, param);
resultCRNList = await crnList.Item1.ToListAsync();

I get an error. The line that reads: crnList = GetCRNList works fine. Here is the code:

    public virtual Tuple<IQueryable<CRN>, int> GetCRNList(bool withRequests = false, IList<int> labIds = null, DTParams param = null, IList<int> crnsWithPropertyLeaseRequests = null)
    {
        IQueryable<CRN> response = null;
        if (withRequests)
        {
            response = GetCRNsWithRequests();
        }
        else
        {
            response = GetCRNsWithoutRequests();
        }

        if (param != null && param.columns != null)
        {
            var filters = param.columns.Where(p => !String.IsNullOrWhiteSpace(p.search.value));
            response = filters.Aggregate(seed: response, func: (r, c) => r.AddCrnFilterExpression(c));

        }
        if (labIds != null && labIds.Count > 0)
        {
            response = response.Where(c => labIds.Any(ul => ul == c.LabId));
        }
        if (crnsWithPropertyLeaseRequests != null)
        {
            response = response.Where(c => crnsWithPropertyLeaseRequests.Any(ul => ul == c.Id));
        }

        var allItems = response.Count();
        if (param != null)
        {
            if (param.order != null)
                response = param.order.Aggregate(seed: response, func: (r, o) => r.AddCrnOrderExpression(o, param.columns));

            response = response.Skip(param.start);
            if (param.length > 0)
                response = response.Take(param.length);
        }
        return new Tuple<IQueryable<CRN>, int>(response, allItems);
    }

it returns an "Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable", for some reason however, the act of turning it into a list causes this error to occur:

SqlNullValueException: Data is Null. This method or property cannot be called on Null values.
    
System.Data.SqlClient.SqlBuffer.get_Int32()
    lambda_method(Closure , DbDataReader )
    Microsoft.EntityFrameworkCore.Storage.Internal.TypedRelationalValueBufferFactory.Create(DbDataReader dataReader)
    Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable<T>+AsyncEnumerator.BufferlessMoveNext(DbContext _, bool buffer, CancellationToken cancellationToken)
    Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync<TState, TResult>(TState state, Func<DbContext, TState, CancellationToken, Task<TResult>> operation, Func<DbContext, TState, CancellationToken, Task<ExecutionResult<TResult>>> verifySucceeded, CancellationToken cancellationToken)
    Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable<T>+AsyncEnumerator.MoveNext(CancellationToken cancellationToken)
    Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider+AsyncSelectEnumerable<TSource, TResult>+AsyncSelectEnumerator.MoveNext(CancellationToken cancellationToken)
    Microsoft.EntityFrameworkCore.Query.Internal.QueryBuffer.IncludeCollectionAsync<TEntity, TRelated, TElement>(int includeId, INavigation navigation, INavigation inverseNavigation, IEntityType targetEntityType, IClrCollectionAccessor clrCollectionAccessor, IClrPropertySetter inverseClrPropertySetter, bool tracking, TEntity entity, Func<IAsyncEnumerable<TRelated>> relatedEntitiesFactory, Func<TEntity, TRelated, bool> joinPredicate, CancellationToken cancellationToken)
    Microsoft.EntityFrameworkCore.Query.Internal.IncludeCompiler+IncludeLoadTreeNodeBase._AwaitMany(IReadOnlyList<Func<Task>> taskFactories)
    Microsoft.EntityFrameworkCore.Query.Internal.IncludeCompiler._IncludeAsync<TEntity>(QueryContext queryContext, TEntity entity, object[] included, Func<QueryContext, TEntity, object[], CancellationToken, Task> fixup, CancellationToken cancellationToken)
    Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.TaskLiftingExpressionVisitor._ExecuteAsync<T>(IReadOnlyList<Func<Task<object>>> taskFactories, Func<object[], T> selector)
    Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider+AsyncSelectEnumerable<TSource, TResult>+AsyncSelectEnumerator.MoveNext(CancellationToken cancellationToken)
    Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider+ExceptionInterceptor<T>+EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)
    System.Linq.AsyncEnumerable.Aggregate_<TSource, TAccumulate, TResult>(IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> accumulator, Func<TAccumulate, TResult> resultSelector, CancellationToken cancellationToken) in Aggregate.cs
    CapexDatabase.Repositories.CRNRepository.CurrentUserCRNSummary<T>(bool refreshCache, DTParams param)
    CapexRequest.Controllers.RequestController.MyCRNSummary(bool refreshCache, string export) in RequestController.cs
    +
                    var userCRNList = await _crnRepo.CurrentUserCRNSummary<CRNModel>(refreshCache);
    Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
    System.Threading.Tasks.ValueTask<TResult>.get_Result()
    System.Runtime.CompilerServices.ValueTaskAwaiter<TResult>.GetResult()
    Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Logged|12_1(ControllerActionInvoker invoker)
    Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
    Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
    Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
    Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
    Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
    Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
    Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
    Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
    Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
    Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

This is very confusing, when I have seen this error in the past its because the model doesn't match the database, but in this case it absoloutely does. So now I am slightly confused.

0 Answers
Related