使用 Azure 應用服務控制臺以編程方式播種資料庫會引發以下錯誤訊息:
SqlException (0x80131904): Cannot insert the value NULL into column 'Id'
但是,以編程方式在本地播種資料庫是沒有錯誤的。可能是什么問題?
失敗的解決方案:
- 將
Id列設定為Nullable直接在資料庫中 [Keyless]用屬性注解物體類Id用屬性注解物體類的[Key]屬性
表架構
------------- --------------- -------------
| 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 |
------------- --------------- -------------
物體類:
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();
}
}
}
}
}
}
uj5u.com熱心網友回復:
您能否檢查源資料的值是否為 NULL 而不是實際的 NULL
類似的情況發生在我身上,其中資料具有 NULL 作為字串值而不是通常的 NULL,整數列不允許這樣的字串
只是為了排除這種可能性,如果您可以在 excel 中提取源資料并檢查任何此類字串值,則可以進行此檢查
uj5u.com熱心網友回復:
問題的根源是該Id列未設定為標識列,因此禁用了該列的自動增量。由于我沒有提供id值,因此資料庫嘗試了 Null 插入并引發了例外。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438400.html
標籤:C# 天蓝色 实体框架核心 天蓝色 sql 数据库 asp.net-core-3.1
