Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core Data Seeding (HasData method on modelBuilder) not inserting data for Identity column

I'm calling the HasData method (see below) for an entity that has an Id (Identity) column, but no data is inserted into the table the first time the Migration runs.

When the TestObject model was not using an Id (Identity) column for the Primary Key, data was inserted as expected the first time the migration was run.

Is EF Core able to insert data for Identity columns?

modelBuilder.Entity<TestObject>().HasData(
            new TestObject
            {
                Id = 1,
                TestValue = "Test 1"
            }
like image 681
Mike Avatar asked Jun 23 '26 12:06

Mike


1 Answers

If the PK column in the database is an Identity Column (created by the database server) then you cannot insert a value. It is generated by the database.

UPDATE

As pointed out in comments below, EF Core will call "SET IDENTITY INSERT ON" when executing HasData().

https://www.learnentityframeworkcore.com/configuration/fluent-api/hasdata-method

like image 112
Neil W Avatar answered Jun 28 '26 10:06

Neil W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!