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

Azure SQL Database throws Null insertion exception

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

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

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

失败的解决方案:

Table 架构

+-------------+---------------+-------------+
| 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,整数列不允许这样的字符串

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

,则可以完成此检查

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