'EF Core Fluent API (How to remove identity from primary key)
Seems simple but I can't figure out how to tell EF core not to create the primary key of an entity with an auto-incrementing identity column. I want to insert my own primary key values myself. I realize I can do this using attributes, but I'd like to know how to set behavior via fluent API. I see the UseSqlServerIdentityColumn() method from the Property() method but I need to turn it off (not on). I've also tried the following code but it doesn't work.
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Employees ON");
context.SaveChanges();
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Employees OFF");
Solution 1:[1]
https://docs.microsoft.com/en-us/ef/core/modeling/generated-properties
modelBuilder.Entity<EntityType>()
.Property( et => et.Id )
.ValueGeneratedNever();
Solution 2:[2]
With attribute it is also possible.
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Moho |
Solution 2 | yilmazhuseyin |