Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is instantiating a GUID in Entity Framework Core bad practice?

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.

like image 648
Mathias Lykkegaard Lorenzen Avatar asked Nov 20 '18 14:11

Mathias Lykkegaard Lorenzen


People also ask

What is GUID in EF core?

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.

What's new in ef6?

Improved compatibility with Roslyn and NuGet PackageReference. Added ef6.exe utility for enabling, adding, scripting, and applying migrations from assemblies. This replaces migrate.exe .

Does EF core 6 require .NET 6?

EF Core 6.0 requires . NET 6.

What is the latest version of Entity Framework Core?

The most recent Entity Framework Core 6.0 (EF Core 6) was released on 10 November 2021.


1 Answers

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.

like image 148
Matías Fidemraizer Avatar answered Oct 22 '22 19:10

Matías Fidemraizer