Kipras
Kipras

Reputation: 163

How to make Entity Framework auto-increment IDs when using code-first

I'm using the code-first approach and because of that I do not have the .edmx file so I cannot change the StoreGeneratedPattern attribute. How do I then make EF auto-increment the IDs? (right now all IDs are zeros by default)

Upvotes: 1

Views: 1850

Answers (2)

phitch
phitch

Reputation: 125

There are three ways to specify keys using EF code first:

  • Use built-in code conventions (his first two bullets)
  • Use the KeyAttribute data annotation directly on the property/field
  • Use the Fluent API to specify the key field

Upvotes: 1

Jaanus Varus
Jaanus Varus

Reputation: 3573

A primary key with auto-increment (default behavior) is generated if any of the following holds true:

  • The class contains a property named "Id"
  • The class contains a property named $className + "Id"
  • The property of interest is annotated with KeyAttribute

Might it be that your property is named "ID" instead of "Id" without the Key attribute?

Upvotes: 1

Related Questions