gpt4 book ai didi

c# - 尝试向表中添加行时无法将 Int32 转换为 null

转载 作者:太空宇宙 更新时间:2023-11-03 19:38:23 27 4
gpt4 key购买 nike

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

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

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

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

我尝试过完全不传递字段,传递字段时不传递任何参数,传递null,所有这些都产生了后来的错误,除了我尝试传递null时,它给了我转换错误。

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

有问题的类:

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

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

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

代码,根据要求:

数据库上下文:

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

Controller :

[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 Server Manager 填充表。它是成功的,然而,这是结果:

weird id

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

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

最佳答案

错误是在将json反序列化为模型时,您有两个选择:

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

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

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

关于c# - 尝试向表中添加行时无法将 Int32 转换为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58501992/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com