尝试向 table 添加行时无法将 Int32 转换为 null

Cannot convert Int32 to null when trying to add a row to table

我正在尝试向 table 添加一行,该行的外键指向同一 table 中的另一个位置。此外键定义为可为空。 尝试向 table 添加条目时出现错误

"errors": {
    "parentId": [
      "Error converting value {null} to type 'System.Int32'. Path 'parentId', line 4, position 18."
    ]
  },

如果我尝试传递一个随机整数,我会得到 The INSERT statement conflicted with the FOREIGN KEY constraint,这是有道理的,因为 table 中没有其他条目。

如您所见,外键被视为可为空。

我试过完全不传字段,传字段时不传入任何参数,传null,都产生了后面的错误,除了我尝试传null的时候,给了我转换错误。

我正在使用 swagger ui 来传递 JSON。

Class 问题:

public class 
{
    public Country Country { get; set; }
    [Required]
    public int CountryId { get; set; }
    [Required]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public int? ParentId { get; set; }
    [ForeignKey("ParentId")]
    public Company Parent { get; set; }     
}

我想在此 table 上创建第一行并将其外键设置为空。

实施答案中建议的修复后,我的错误从转换错误变为上述外部约束错误,即使传递空值也是如此。

代码,根据要求:

数据库上下文:

public class ArtGalleriesContext:DbContext
{
    public ArtGalleriesContext(DbContextOptions<ArtGalleriesContext> options):base(options)
    {

    }

    public DbSet<ArtItem> ArtItems { get; set; }
    public DbSet<Artist> Artists { get; set; }
    public DbSet<Company> Companies { get; set; }
    public DbSet<Country> Countries { get; set; }
    public DbSet<Floor> Floors { get; set; }
    public DbSet<Location> Locations { get; set; }
    public DbSet<Room> Rooms { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<UserLocation> UserLocations { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.Entity<UserLocation>()
            .HasKey(u => new {u.UserId, u.LocationId});
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(
                "Server=(localdb)\mssqllocaldb;Database=GalleriesDB;Trusted_Connection=True;");
        }
    }
}

控制器:

[HttpPost("Companies")]
public IActionResult CreateCompany([FromBody]CreateCompanyRequest createCompanyRequest)
{
    try
    {
        if (createCompanyRequest==null)
        {
            return NotFound();
        }

        return CreatedAtRoute("CompanyById", _repository.Company.CreateCompany(createCompanyRequest),
            createCompanyRequest);
    }
    catch (Exception e)
    {
        return StatusCode(500, e.InnerException);
    }
}

存储库:

public int CreateCompany(CreateCompanyRequest createCompanyRequest)
{
    Company company = new Company()
    {
        CountryId = createCompanyRequest.CountryId,
        Name = createCompanyRequest.Name,
        ParentId = createCompanyRequest.ParentId
    };
    _context.Companies.Add(company);
    _context.SaveChanges();
    return company.Id;
}

可能相关的信息:我尝试使用 Microsoft SQL 服务器管理器填充 table。成功了,但是结果是这样的:

显然有问题,因为它开始添加从 PK 14 开始的条目。

进一步检查后,我注意到即使向table添加一行失败,主键仍然递增。

根据您的用例,您可能还需要考虑 JSON Serializer ignore nulls

或使用"JsonProperty"属性:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int? ParentId { get; set; }

错误是在反序列化json到模型时,你有两个选择:

  1. 添加到您的 startup.cs class Json 选项以忽略空值,如下所示:

    .AddJsonOptions(options =>
     {
         options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore
     });
    
  2. 在 属性 本身上设置为忽略空值,因此它将 int? 初始化为空值

    public class 
    {
       public Country Country { get; set; }
       [Required]
       public int CountryId { get; set; }
       [Required]
       public int Id { get; set; }
       [Required]
       public string Name { get; set; }
       [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
       public int? ParentId { get; set; }
       [ForeignKey("ParentId")]
       public Company Parent { get; set; }     
    }
    

问题可以通过以上两个答案解决,而且,我注意到我只在我的实体 class 中声明 ParentId 为可空 int,而不是在我的模型中,CreateCompanyRequest;在模型中更改它的类型解决了这个问题。

转换问题是因为我尝试在模型 class 中传递空值,其中包含一个 int prop,而不是可为空的 int prop。