If I have a model with a key of type Guid
, is it bad practise to set the ID explicitly in the constructor?
I know it will be set implicitly by Entity Framework, but will anything bad happen (perhaps performance wise) from setting it explicitly?
Example:
class MyModel
{
public MyModel()
{
Id = Guid.NewGuid();
}
[Key]
public Guid Id { get; set; }
}
I'm thinking a Guid
is backed up by a sequential ID in SQL server, and if I set a value explicitly, I suppose I will decrease indexing performance because it will no longer be sequential?
I have not been able to find an answer on this and I am highly curious about it.
GUID primary keys are usually required, when you need meaningful primary keys before inserting data in database (e.g., there are client apps, that later synchronize data with main database). In other words, the only advantage from GUID PK is ability to generate it at client side.
Improved compatibility with Roslyn and NuGet PackageReference. Added ef6.exe utility for enabling, adding, scripting, and applying migrations from assemblies. This replaces migrate.exe .
EF Core 6.0 requires . NET 6.
The most recent Entity Framework Core 6.0 (EF Core 6) was released on 10 November 2021.
I see a design flaw rather than a performance problem: models shouldn't generate their id
. It's out of their responsibility. Repositories do so in the Add
method.
Guid
can be generated in many ways: for example, it can be random or sequential. There're different algorithms to generate them either way. Therefore, you're closing your choices to just one.
And you're forcing the moment on which the model id
is assigned: you mighn't want this in order to delay its assignment until the model may need to be persisted. For example, a zero Guid
may be useful to know that some model isn't persistent yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With