Why EF Core 2.2 has a default primary key set to nvarchar(450)
Asked Answered
R

2

9

We are upgrading our code base from EF6.2 to EF Core 2.2, our team discovered that the default value of string based Identity key will generate a primary key column with

  • nvarchar(128) in EF 6.2 (SQL Server)
  • nvarchar(450) in EF Core 2.2 (SQL Server)

What is the reason behind this decision?

Rhotacism answered 22/8, 2019 at 4:42 Comment(3)
Seems like a provider thing more than an EF thingSofty
Let us say you get the answer to your question - how will it help you? In other words, I think this is a XY Problem (meta.stackexchange.com/questions/66377/what-is-the-xy-problem).Internalize
In sql server database it is not allowed to create Unique constraint against column with its type as nvarchar(max). It should be limited to some number, someone choose nvarchar(128) before, then someone change to nvarchar(450). I realised that it must be some reason behind but I don't know. Just a curious of developerRhotacism
M
23

SQL Server allows indexes up to 900 bytes. Characters in an nvarchar are 2 bytes. 2 * 450 = 900. We (the EF team) were worried about primary keys on multiple columns in EF6. In EF Core, we realized only specified characters are indexed ("var" is for varying length) so we could go all the up to 450 and it would still work so long as the total characters across all columns in the key were less than 450.

Morehead answered 22/8, 2019 at 15:14 Comment(0)
F
0

This sounds like a custom configuration in your application as the default configuration for Entity Framework would expect a an integer Id.

As for Why? This would have been a design decision by the developer at the time. This will also depend on how long ago that was implemented and if the database was originally created before Entity Framework was implemented or indeed .Net was implemented.

I have seen implementations that started as classic ASP web apps, where GUIDs or string Id values were used as Ids, so users could not guess the URLs to get data. This would be seen as very weak security these days, but was used in the past.

It would be possible to add an integer Identity field and then set this in configuration as the Id that Entity Framework would use:

// Set Id Property as Key Property for all entities
            modelBuilder
                .Properties()
                .Where(p => p.Name == "Id")
                .Configure(p => p.IsKey());
Flammable answered 22/8, 2019 at 5:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.