Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core Fluent API (How to remove identity from primary key)

Tags:

ef-core-2.1

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");
like image 869
Geekn Avatar asked Sep 16 '18 00:09

Geekn


People also ask

How do you configure a primary key for an entity in Entity Framework fluent API?

Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.

How do you set composite primary key in fluent API?

The only way to configure composite keys is to use the HasKey method. You specify the properties that form the composite key by passing them in as properties of an anonymous type to the HasKey method.

How do I change the default value for EF core?

In EF core released 27th June 2016 you can use fluent API for setting default value. Go to ApplicationDbContext class, find/create the method name OnModelCreating and add the following fluent API.


1 Answers

https://docs.microsoft.com/en-us/ef/core/modeling/generated-properties

modelBuilder.Entity<EntityType>()
    .Property( et => et.Id )
    .ValueGeneratedNever();
like image 146
Moho Avatar answered Sep 22 '22 06:09

Moho