[go: up one dir, main page]
More Web Proxy on the site http://driver.im/

DEV Community

Cover image for Entity Framework(EF) Enum issue/bug/feature
TSOTSI1
TSOTSI1

Posted on

Entity Framework(EF) Enum issue/bug/feature

There is an issue that I have faced before with the Entity Framework (EF) issue/feature for enums. Even though I used .HasDefaultValue() of EF Core, it still did not work.

Image description

The issue at hand is as follows:
https://github.com/dotnet/efcore/issues/15070

When a developer uses an enum as an attribute of a column, the default value will always be the first enum, which is usually 0, and cannot be updated. How can we avoid this issue until the feature is fixed or modified? Here are two possible solutions below.


1. Assign specific number(exclude 0) to Enum

public enum State
{
    Walking = 1,
    Reading = 2,
    Drinking = 3,
}
Enter fullscreen mode Exit fullscreen mode

Pros: The solution is clear and easy to understand.

Cons: It requires maintenance, as every individual needs to assign a specific number to the enum value.

2. Make default value as the first attribute of enum

public enum State
{
    Walking,
    Reading,
    Drinking,
}
Enter fullscreen mode Exit fullscreen mode

Pros: There's no need to assign a number, and the enum remains clean.

Cons: To prevent someone from modifying the enum without understanding, test cases are needed.


Summary

I personally used the approach of making the default value the first attribute of the enum. In my opinion, this is a cleaner approach and it only requires one test case to ensure that the order is not accidentally changed.

On the other hand, assigning a specific number (excluding 0) to each enum attribute can be a big effort, especially if an enum has over 100 attributes. It can become quite messy.

Ultimately, it's important to pick one approach to ensure that the data in the database is what you want. Any discussions on this topic are welcome. Thank you!

Top comments (0)