I made a few tables in EF and entered in some seed data where I give value to a few columns with a primary key. When I run the application I am getting the error message: <
Had to deal with the same issue and this seems to be a clean solution.
Credit to >> https://github.com/dotnet/efcore/issues/11586
I have made some changes so it now works with .Net Core 3.1 + (Tested in .Net 5) and also added this Method SaveChangesWithIdentityInsert
public static class IdentityHelpers
{
public static Task EnableIdentityInsert(this DbContext context) => SetIdentityInsert(context, enable: true);
public static Task DisableIdentityInsert(this DbContext context) => SetIdentityInsert(context, enable: false);
private static Task SetIdentityInsert(DbContext context, bool enable)
{
var entityType = context.Model.FindEntityType(typeof(T));
var value = enable ? "ON" : "OFF";
return context.Database.ExecuteSqlRawAsync(
$"SET IDENTITY_INSERT {entityType.GetSchema()}.{entityType.GetTableName()} {value}");
}
public static void SaveChangesWithIdentityInsert(this DbContext context)
{
using var transaction = context.Database.BeginTransaction();
context.EnableIdentityInsert();
context.SaveChanges();
context.DisableIdentityInsert();
transaction.Commit();
}
}
Usage
var data = new MyType{SomeProp= DateTime.Now, Id = 1};
context.MyType.Add(data);
context.SaveChangesWithIdentityInsert();