数据为空。不能对 Null 值调用此方法或属性 - Data.SqlTypes.SqlNullValueException

问题描述 投票:0回答:1

我有一个问题,当我将我的项目 asp .net core 2.1 更新到 3.1 时,当您尝试发送一些数据时,我的项目角度总是出现此错误。

ClassName: "System.Data.SqlTypes.SqlNullValueException"
Data: null
ExceptionMethod: null
HResult: -2146232015
HelpURL: null
InnerException: null
Message: "Data is Null. This method or property cannot be called on Null values."
RemoteStackIndex: 0
RemoteStackTraceString: null
Source: "Microsoft.Data.SqlClient"
StackTraceString: "   at Microsoft.Data.SqlClient.SqlBuffer.ThrowIfNull()\r\n   at Microsoft.Data.SqlClient.SqlBuffer.get_String()\r\n   at Microsoft.Data.SqlClient.SqlDataReader.GetString(Int32 i)\r\n   at lambda_method(Closure , QueryContext , DbDataReader , ResultContext , Int32[] , ResultCoordinator )\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()\r\n   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\r\n   at MotorCredito.Pegasus.Persistence.Repository.MantenimientoLogsRepository.GetIdRegistro() in C:\\Repositorios MC\\Pegasus\\MotorCredito.Pegasus.Persistence\\Repository\\Logs\\MantenimientoLogsRepository.cs:line 91\r\n   at MotorCredito.Pegasus.Web.Controllers.MarcasController.Update(String usuario, Marca marca) in C:\\Repositorios MC\\Pegasus\\MotorCredito.Pegasus.Web\\Controllers\\MarcasController.cs:line 138"
WatsonBuckets: null

这是我在 Startup.cs 中的 ConfigureService

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = null;
        options.JsonSerializerOptions.IgnoreNullValues = true;
       // options.JsonSerializerOptions.

    });

    //FORMA NUEVA
    services.AddControllers(options =>
    {
        options.EnableEndpointRouting = true;
        options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true;
        options.AllowEmptyInputInBodyModelBinding = true;

    })
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
        options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
        options.SerializerSettings.DateFormatString = "dd-MM-yyyy";
    });

    // ===== Add DbContext Configuration for PegasusDbContext ========
    services.AddDbContextPool<PegasusDbContext>(options =>
       options.UseSqlServer(Configuration.GetConnectionString("PegasusDb")));

    // ===== Add DbContext Configuration for ServicesDbContext========
    services.AddDbContextPool<ServicesDbContext>(options =>
       options.UseSqlServer(Configuration.GetConnectionString("ServicesDb"),
       sqlServerOptions => sqlServerOptions.CommandTimeout(180)));

这是我的功能配置

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

    app.UseAuthentication();

    app.UseSession();

    app.UseHttpsRedirection();

    //se agrego esto
    app.UseRouting();

    //se agrego esto
    app.UseAuthorization();

    app.UseFileServer();

    //se agrego esto
    app.UseEndpoints(endPoints =>
    {
        endPoints.MapHub<UserInSolicitudHub>("/UserInSolicitud");
        endPoints.MapControllerRoute(
              name: "default",
           pattern: "{controller=Home}/{action=Index}/{id?}"
           );
    });


    //app.UseAzureSignalR(routes =>
    //{
    //    routes.MapHub<UserInSolicitudHub>("/UserInSolicitud");
    //});
}

我试图在函数 ConfigureServices 中进行一些配置,但我遇到了另一个错误。

c# angular asp.net-core-3.1 asp.net-core-2.1
1个回答
0
投票

我的回答有点晚了,但我刚遇到同样的问题,并找到了根本原因。

此错误通常是由于代码优先实体框架引起的,当您的实体模型未正确定义并且与数据库架构和数据不匹配时。

特别是在 .Net 中的值类型属性,如 INT 不能为 NULL。

我的具体例子;

我的数据库有一列;

  • AccountId INT NULL

我的 EF 模型对象有一个属性;

  • public AccountId int { get;放; }

我试图加载一个对象,其中 AccountID 的值为 NULL。

问题是,当 EF 尝试将 NULL 放入值类型时,它会抛出 SqlNullValueException。

修复 - DB

数据库修复将按如下方式制作列;

  • AccountId INT 不为空

修复 - EF 模型

或者您可以使用可空类型修复模型

  • 公共情报?账户ID { 得到;放; }

无论哪种方式,EF 模型现在都与您的数据库模式匹配,您将不再收到此错误。

希望这有帮助

© www.soinside.com 2019 - 2024. All rights reserved.