Is instantiating a GUID in Entity Framework Core bad practice?

c# entity-framework-core guid

Question

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.

1
9
11/21/2018 3:00:24 AM

Accepted Answer

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.

11
11/20/2018 2:13:42 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow