I have json data with Ids, my goal is to take the json data and insert into database using Entity Framework, with the same id set as I'm using them as a foreign key in different table. But the problem is I'm getting error
Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table 'ProductTypes' when IDENTITY_INSERT is set to OFF.
which means IDENTITY_INSERT
is set to OFF
and I don't get why as I'm using
dbContext.Database.ExecuteSqlRaw("SET IDENTITY_INSERT dbo.ProductTypes ON");
command to make sure it's set to on.
public class ApplicationDbContextSeed
{
public static async Task SeedAsync(ApplicationDbContext dbContext, ILoggerFactory loggerFactory)
{
try
{
if (!dbContext.ProductTypes.Any())
{
var typesData = File.ReadAllText("../Infrastructure/Data/SeedData/types.json");
var types = JsonSerializer.Deserialize<List<ProductType>>(typesData);
dbContext.Database.ExecuteSqlRaw("SET IDENTITY_INSERT dbo.ProductTypes ON");
foreach (var item in types)
{
dbContext.ProductTypes.Add(item);
}
await dbContext.SaveChangesAsync();
dbContext.Database.ExecuteSqlRaw("SET IDENTITY_INSERT dbo.ProductTypes OFF");
}
}
catch (Exception ex)
{
var logger = loggerFactory.CreateLogger<ApplicationDbContextSeed>();
logger.LogError(ex.Message);
}
}
}