繁体   English   中英

Azure SQL 数据库抛出 Null 插入异常

[英]Azure SQL Database throws Null insertion exception

使用 Azure 应用服务控制台以编程方式为数据库播种会引发以下错误消息:

SqlException (0x80131904): Cannot insert the value NULL into column 'Id'

但是,以编程方式在本地为数据库播种是没有错误的。 可能是什么问题?

失败的解决方案:

  • 直接在数据库中将Id列设置为Nullable
  • [Keyless]属性注释实体 class
  • [Key]属性注解实体类的Id属性

表模式

+-------------+---------------+-------------+
| Table Name: Cities                        |
+-------------+---------------+-------------+
| Column Name |   Data Type   | Allow Nulls | 
+-------------+---------------+-------------+
| Id (PK)     | int           |     NO      |
| CityCode    | int           |     NO      |
| Name        | nvarchar(MAX) |     YES     |
| State       | nvarchar(MAX) |     YES     |
| Country     | nvarchar(MAX) |     YES     | 
+-------------+---------------+-------------+

实体 Class:

public class City
{
  public int Id { get; set; }
  public int CityCode { get; set; }
  public string Name { get; set; }
  public string State { get; set; }
  public string Country { get; set; }
}

播种代码:

public class DbInitializer : IDbInitializer
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly IWebHostEnvironment _hostEnvironment;

    public DbInitializer(IServiceScopeFactory scopeFactory, IWebHostEnvironment environment)
    {
        _scopeFactory = scopeFactory;
        _hostEnvironment = environment;
    }

    public void Initialize()
    {
        using (var serviceScope = _scopeFactory.CreateScope())
        {
            using (var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>())
            {
                context.Database.EnsureCreatedAsync();
            }
        }
    }

    public async Task SeedData()
    {
        using (var serviceScope = _scopeFactory.CreateScope())
        {
            using (var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>())
            {
                if (!context.Cities.Any())
                {
                    string path = Path.Combine(_hostEnvironment.WebRootPath, "citylist.json");
                    using (StreamReader reader = new StreamReader(path))
                    {
                        string jsonData = reader.ReadToEnd();
                        List<City> cityList = JsonConvert.DeserializeObject<List<City>>(jsonData);
                        await context.Cities.AddRangeAsync(cityList);
                        await context.SaveChangesAsync();
                    }
                }
            }
        }
    }
}

您能否检查源数据的值是否为 NULL 而不是实际的 NULL

类似的情况发生在我身上,数据有 NULL 作为字符串值,而不是通常的 NULL,integer 列不允许这样的字符串

只是为了排除这种可能性,如果您可以提取 excel 中的源数据并检查任何此类字符串值,则可以完成此检查

问题的根源是Id列未设置为标识列,因此禁用了该列的自动递增。 由于我没有提供id值,数据库尝试插入 Null 并抛出异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM