Entityframework.docs: Primary key types

Created on 9 Oct 2018  Â·  10Comments  Â·  Source: dotnet/EntityFramework.Docs

It would be nice to have a discussion of the recommended type choice(s) for primary keys. The docs here use string but what about int, uint, long, and so on? Are there types that are not allowed as primary keys?


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

area-model-building closed-fixed

Most helpful comment

Related, it would be good to at least link to the Generated Values page because there's valuable information regarding keys there: "By convention, non-composite primary keys of type short, int, long, or Guid will be setup to have values generated on add. All other properties will be setup with no value generation."

All 10 comments

What about composite keys? Seems like a basic use case that should be covered here. Specifically, are there annotations for that?

https://medium.com/radzenhq/how-to-entity-framework-core-relationships-composite-keys-foreign-keys-data-annotations-code-f4b238086463
for anyone searching for composite keys, you first define two or more of the columns required as the composite key as [Key] in the class and then specify them in model by overriding the following method in DBContext

protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity().HasKey(table => new {
table.OrderID, table.ProductID
});
}

@kkarakk Using the [Key] attribute in that case should not be needed.

I'm surprised at the docs '...conventions will never setup a composite key...', EF6 did it why can't core. Surely the principles are the same. Using composite keys is very common in a multitenancy environment.

@eeegs Can you remind me in what conditions EF6 creates a composite key by convention?

@ajcvickers: My bad, I was thinking attributes when I read that in the doco. Because at the moment even multiple '[Key, Column(order=n)]' can't be used. Sorry never by convention will always be correct.

I would say GUID would be a good fit for an ID, if you plan to work with a large amount of records

Guids for PK are only acceptable if they are mostly sequentially generated.

Related, it would be good to at least link to the Generated Values page because there's valuable information regarding keys there: "By convention, non-composite primary keys of type short, int, long, or Guid will be setup to have values generated on add. All other properties will be setup with no value generation."

From https://github.com/aspnet/EntityFrameworkCore/issues/18055 ensure that it is clear when a key property gets generated values by default, and when not.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

norvegec picture norvegec  Â·  3Comments

divega picture divega  Â·  4Comments

jpeckham picture jpeckham  Â·  3Comments

speciesunknown picture speciesunknown  Â·  3Comments

SychevIgor picture SychevIgor  Â·  4Comments