如何解决 SqlNullValueException?

Fri*_*iso 6 c# sql-server entity-framework entity-framework-core .net-core

我正在尝试查找实体,但是当实体框架尝试获取 Null 字段的值时,我收到了 SqlNullValueException。

我检查了数据库,并填充了所有不可为空的字段。唯一具有 NULL 值的字段是允许拥有它的字段。

在其他答案中,我发现我应该从类属性中删除 required 属性或从模型构建器定义中删除 IsRequired 方法,但是我自动生成了这些并且它们从来没有必需的定义。

我的应用程序在 .NET Core 3.1 上运行,而我的 EntityFrameworkCore 版本是 2.2.4。即使它成功构建,这是否会导致问题?更新现在所有版本都是 3.1。

如果不是,还有什么可能导致它?

要查找实体,我使用以下方法:

public static CodeLists FindCodeListById(Guid id)
{
    using (var context = new classificatielocalContext())
    {
        return context.CodeLists.Find(id);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下异常:

System.Data.SqlTypes.SqlNullValueException

HResult=0x80131931

消息=数据为空。不能对 Null 值调用此方法或属性。

源 = System.Data.Common

堆栈跟踪:

System.Data.SqlTypes.SqlGuid.get_Value()

System.Data.SqlClient.SqlDataReader.GetGuid(Int32 i)

Microsoft.EntityFrameworkCore.Storage.Internal.TypedRelationalValueBufferFactory.Create(DbDataReader dataReader)

Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)`

Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 操作时,Func3 verifySucceeded)

Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext()`

System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable1 个来源,布尔值&找到)`

Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable1.GetEnumerator()`

Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__172.MoveNext()`

Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext()`

System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable1 个来源,布尔值&找到)`

System.Linq.Enumerable.First[TSource](IEnumerable1 个来源)`

Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_11.b__0(QueryContext qc)`

Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)

Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)

System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 个来源,表达1 predicate)

Microsoft.EntityFrameworkCore.Internal.EntityFinder1.Find(Object[] keyValues)`

Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.Find(Object[] keyValues)`

dal.Views.FindCodeListById(Guid id)中...

services.CodeListService.GetCodeList(Guid id) 中...

api.Controllers.CodeListController.Get(Guid id)中...

Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)

Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)

Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeActionMethodAsync>g__Logged|12_1>d.MoveNext()

OnModelCreating(ModelBuilder modelBuilder)用来定义我的实体,但我没有在哪里定义我的列是必需的。

这是我的模型构建器定义:

modelBuilder.Entity<CodeLists>(entity =>
{
    entity.HasKey(e => e.Id)
        .ForSqlServerIsClustered(false);

    entity.ToTable("code_lists");

    entity.Property(e => e.Id)
        .HasColumnName("id")
        .HasDefaultValueSql("(newsequentialid())");

    entity.Property(e => e.ClassificationId).HasColumnName("classification_id");

    entity.Property(e => e.DescriptionId).HasColumnName("description_id");

    entity.Property(e => e.NameId).HasColumnName("name_id");

    entity.Property(e => e.OwnerId).HasColumnName("owner_id");

    entity.HasOne(d => d.Classification)
        .WithMany(p => p.CodeLists)
        .HasForeignKey(d => d.ClassificationId)
        .OnDelete(DeleteBehavior.ClientSetNull)
        .HasConstraintName("FK__code_list__class__5FB337D6");

    entity.HasOne(d => d.Description)
        .WithMany(p => p.CodeListsDescription)
        .HasForeignKey(d => d.DescriptionId)
        .HasConstraintName("FK__code_list__descr__60A75C0F");

    entity.HasOne(d => d.Name)
        .WithMany(p => p.CodeListsName)
        .HasForeignKey(d => d.NameId)
        .OnDelete(DeleteBehavior.ClientSetNull)
        .HasConstraintName("FK__code_list__name___619B8048");

    entity.HasOne(d => d.Owner)
        .WithMany(p => p.CodeLists)
        .HasForeignKey(d => d.OwnerId)
        .OnDelete(DeleteBehavior.ClientSetNull)
        .HasConstraintName("FK__code_list__owner__628FA481");
});
Run Code Online (Sandbox Code Playgroud)

这是我的 sql 定义

CREATE TABLE [dbo].[code_lists]
(
    [id] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY NONCLUSTERED DEFAULT NEWSEQUENTIALID(),
    [classification_id] UNIQUEIDENTIFIER NULL FOREIGN KEY REFERENCES classifications(id), -- TODO: Should be set to NOT NULL
    [description_id] UNIQUEIDENTIFIER FOREIGN KEY REFERENCES translations(id),
    [name_id] UNIQUEIDENTIFIER NOT NULL FOREIGN KEY REFERENCES translations(id),
    [owner_id] UNIQUEIDENTIFIER NULL FOREIGN KEY REFERENCES users(id), -- TODO: Should be set to NOT NULL
)
Run Code Online (Sandbox Code Playgroud)

更新 更新版本并添加 nuget 包后System.Data.SqlClient,堆栈跟踪更改为:

System.Data.SqlTypes.SqlNullValueException

HResult=0x80131931

消息=数据为空。不能对 Null 值调用此方法或属性。

源 = Microsoft.Data.SqlClient

堆栈跟踪:

Microsoft.Data.SqlClient.SqlBuffer.ThrowIfNull()

Microsoft.Data.SqlClient.SqlBuffer.get_Guid()

Microsoft.Data.SqlClient.SqlDataReader.GetGuid(Int32 i)

Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext()`

System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 个来源)`

Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)

Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)

System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 个来源)`

cbs.classifications.dal.Views.FindCodeListById(Guid id)中...

cbs.classifications.services.CodeListService.GetCodeList(Guid id)中...

cbs.classifications.api.Controllers.CodeListController.Get(Guid id)

Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)

Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)

Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeActionMethodAsync>g__Logged|12_1>d.MoveNext()

更新的CodeLists 类

public partial class CodeLists
{
    public CodeLists()
    {
        Levels = new HashSet<Levels>();
        Nodes = new HashSet<Nodes>();
    }

    public Guid Id { get; set; }
    public Guid ClassificationId { get; set; }
    public Guid? DescriptionId { get; set; }
    public Guid NameId { get; set; }
    public Guid OwnerId { get; set; }

    public Classifications Classification { get; set; }
    public Translations Description { get; set; }
    public Translations Name { get; set; }
    public Users Owner { get; set; }
    public ICollection<Levels> Levels { get; set; }
    public ICollection<Nodes> Nodes { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Duc*_*ing 9

我的问题是我Nullable在类库项目中启用了该功能。删除Nullable节点修复了它。EFCore 不再抛出错误,并且警告从我的模型中消失。

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
Run Code Online (Sandbox Code Playgroud)


ole*_*ksa 8

您必须使用CodeLists可空数据类型标记所有可空属性,如下所示:

public class CodeLists
{
    public Guid Id { get; set; }
    public Guid? ClassificationId { get; set; }
    public Guid? DescriptionId { get; set; }

    public Guid NameId { get; set; }
    public Guid? OwnerId { get; set; }

}

Run Code Online (Sandbox Code Playgroud)

ClassificationId并且OwnerId在类实现中不可为空CodeLists,但在数据库中可为空