• API
    • CPF
  • Blog
  • Contact

Contact Us

Give us a call or fill in the form below and we will contact you. We endeavor to answer all inquiries within 24 hours on business days.

Edit Content

     

    Technology

    Enum Keys Revolution: A Smarter Way to Manage Static Entities in Your Application

    January 9, 2025 Weslei Gomes de Sousa, Bruno de Souza Melo

    Imagine managing a database with countless static entities like status codes or user roles, where every change or lookup feels cumbersome and prone to errors. Traditional approaches using int or short primary keys can make the codebase harder to read and maintain, leading to inefficiencies and potential mistakes. But what if there were a simpler, more intuitive way to handle these entities? Using enums offers a streamlined solution, improving both readability and development efficiency. We will explore how to implement enums as primary keys and dive into the advantages and potential trade-offs of this pattern.

    Disadvantages of Using Numeric or Generic Primary Keys

    While using generic primary key types (such as `int`, `short`, or `guid`) is a common practice, it has several drawbacks for static entities:

    1. Lack of Readability: Numeric IDs or GUIDs do not convey meaningful information. For example, seeing `1`, `2`, or a long GUID string in code gives no immediate indication of what it represents.
    2. Higher Risk of Errors: Hardcoding generic values in code increases the risk of using incorrect identifiers, especially when there are changes in the database or schema.
    3. Poor Maintainability: Developers must constantly reference documentation or database tables to understand what a specific value represents.
    4. Overhead in Mapping: When using generic primary keys, additional mappings or comments in the codebase are often required to make the identifiers meaningful, adding extra complexity.

    Benefits of Using Enums as Primary Keys for Fixed Tables

    Using enums as primary keys offers several advantages:

    1. Improved Readability: Enums use descriptive names for values, making the code easier to understand.
    2. Type Safety: Enums ensure only valid values can be used, reducing the risk of runtime errors.
    3. Consistency: Enums keep the database and code synchronized, making it easier to maintain.
    4. Ease of Refactoring: Changes to enums in code automatically reflect in the database, ensuring consistency without requiring additional effort.
    5. Simplified Coding: Enums eliminate the need to write extra code for mapping numeric IDs to meaningful names.
    6. Memory Optimization: By using a smaller base type, such as `short`, enums can reduce memory usage when dealing with large datasets.

    How to Configure Enums as Primary Keys

    Here’s a step-by-step guide to using enums as primary keys in a C# application with Entity Framework (EF):

    1. Define the Enum:
    public enum UserRole : short
    {
        Admin = 1,
        User = 2,
        Guest = 3
    }

    In this example, the enum is explicitly defined with a base type of `short`, which means the underlying storage type of the enum values will be a `short` (16-bit integer). This can be useful when optimizing for memory usage, especially in scenarios where large volumes of data are involved, or when aligning with existing database schemas that use `smallint`.

    1. Create the Entity Model:
    public class Role
    {
        public UserRole Id { get; set; }
        public string Name { get; set; }
    }
    1. Configure the Database Context:
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Role>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.Property(e => e.Id).HasConversion<short>().ValueGeneratedNever();
    
            entity.Property(e => e.Name)
                  .IsRequired()
                  .HasMaxLength(50);
        });
    }

    The `HasConversion<short>()` method ensures the enum is stored as a `smallint` in the database.

    1. Seed the Database:
    modelBuilder.Entity<Role>().HasData(
        new Role { Id = UserRole.Admin, Name = "Administrator" },
        new Role { Id = UserRole.User, Name = "Standard User" },
        new Role { Id = UserRole.Guest, Name = "Guest User" }
    );

    How It Works

    When using enums as primary keys, the framework (e.g., Entity Framework) maps the enum to its underlying numeric type (e.g., `short`) in the database. This allows developers to work with enums in the codebase while storing compact numeric values in the database. Queries, inserts, and updates automatically handle the conversion between the enum and its numeric representation.

    var adminRole = dbContext.Roles.Find(UserRole.Admin);
    Console.WriteLine(adminRole.Name); // Output: Administrator

    The `Find` method uses the enum value `UserRole.Admin` to locate the corresponding record in the database, making the code intuitive and maintainable.

    Conclusion

    Using enums as primary keys for static entities provides significant benefits, including improved code readability, type safety, maintainability, and memory optimization. By specifying a smaller base type, such as `short`, you can further optimize database storage without sacrificing functionality. By following the steps outlined above, you can seamlessly integrate enums into your database schema, reducing errors and simplifying your code. This approach is especially suitable for fixed data entities, ensuring consistency between your database and application.

    • Weslei Gomes de Sousa

      With over 20 years of experience in IT solutions architecture, has strong expertise in .NET and Azure and high proficiency in managing relational and non-relational databases. Techs: Azure Architecture, Azure DevOps (CI/CD, Artifacts, Git), Docker, Azure Storage, B2C, Azure Service Bus, RabbitMQ, AWS Cloud, Web Applications/Frontend (Angular, Blazor, React, Razor Pages), TypeScript, Python, ASP.NET Web API (REST), MAUI (Mobile Development), Entity Framework Core, C#, Windows Applications (WPF, WinForms, UWP), Java, among others.

    • Bruno de Souza Melo

      Over 20 years of experience delivering innovative IT solutions for public and private sectors, enhancing user welfare and societal impact.

      Expertise
      Development & Infrastructure: Extensive experience with Visual Studio (2003–2022), Azure, GCP, AWS, messaging platforms (Azure Service Bus, Pub/Sub, RabbitMQ), Azure DevOps (CI/CD, Git, Artifacts), Docker, Microsoft 365, SharePoint, IntelliJ IDEA, and more.
      Data Tools: Proficiency in Spark, Jupyter/Zeppelin, and Hue for Impala/Hive (HDFS). Databases: Skilled in Microsoft SQL Server, PostgreSQL, MongoDB, Oracle, and others.
      Technologies & Languages: Expertise in web development (Blazor, React, Angular, Razor Pages), TypeScript, Python, ASP.NET Web API, Xamarin, Entity Framework Core, C#, Java/Spring, and Windows applications (WPF, WinForms, UWP).

      Methodologies & Architecture
      Agile methodologies (Scrum, Kanban) for efficient project management. Solution architecture, including business modeling (BPMN, C4 Model) and technology frameworks (Clean Architecture).

      Industry Experience
      Diverse domain knowledge across fast food, transportation, banking, hospitality, contracts, and more.

    Post navigation

    Previous
    Next

    Search

    Categories

    • Technology (7)

    Recent posts

    • State Management in Blazor: Best Practices and Strategies
    • Understanding obj == null vs obj is null in C# and Their Performance Impact
    • 500x Faster: Avoid Queries in Loops with C# Entity Framework for Peak Performance

    Tags

    #ai #artificialintelligence #judiciary #speedtrial #ai #artificialintelligence #publicsector BestPractices Blazor c# CleanCode converter CSharp dataperformance datetime DotNet ef entity entityframework enum highperformance json keys nuvtools nuvtools.common serialization Web

    Related posts

    Technology

    500x Faster: Avoid Queries in Loops with C# Entity Framework for Peak Performance

    January 26, 2025 Weslei Gomes de Sousa, Bruno de Souza Melo

    Executing database queries inside a loop is a common mistake that leads to significant performance issues, mainly in high-scale systems. Each iteration of the loop triggers a separate database query, resulting in: For example, consider the following code in C# utilizing Entity Framework Core: This approach executes one query for each user ID in the […]

    Fuel your business growth and witness immediate results today.

    Menu
    • Home
    • API
    • Blog
    • Contact

    © Nuv Tools Technology. All Rights Reserved.

    © Nuv Tools Technology.
    All Rights Reserved.