You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core 2调用ToListAsync触发SqlNullValueException问题求助

EF Core 2 SqlNullValueException排查求助

我正在使用Entity Framework Core 2,给模型新增了三个可空int类型字段:

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

数据库对应列也设置为可空,但执行以下代码将IQueryable集合转换为列表时:

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

触发了SqlNullValueException异常:"Data is Null. This method or property cannot be called on Null values."

此前遇到该异常均是因为模型与数据库不匹配,但本次两者配置一致,特此求助排查原因。

GetCRNList方法代码

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);
}

完整异常栈信息

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)

内容的提问来源于stack exchange,提问作者Keeko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:15:42