Can Enums in C# can be use of replacement of Lookup tables(e.g SportType,MatchType)

231 views Asked by At

I have some table in database.Taking about only two

1-Sports
2-Match<>
.......
In sports table there is columns SportType<br>
and In Match table there is column MatchType

Option 1:
I have option to create SportType and MatchType Table

Option 2:
and second option is to crate Enums of SportType and MatchType

Some people don't prefer option 1 due to extra joins in query
What you suggest

I also need to show SportType & MatchType in DropDownLists

2

There are 2 answers

0
Jay On

You need to consider several factors when deciding between lookup tables and enums or similar in-code constants. Principal among those factors is the question of how likely it is that you would have to add or modify any of those values without redeploying the application.

Another thing to keep in mind is that if you use in-code values, you won't likely be using any kind of surrogate key, so if you ever decided to change the spelling of something in your code, you might create a problem with mismatched data in the database.

Since you also need to show these types in dropdown lists, I'll advise against using bare enums, as it gets hacky to display UI-friendly versions (with spaces between words, for example).

The simplest alternative is a class with string constants:

public class SportType
{
    public const string TeamSport = "Team Sport";
    public const string IndividualSport = "IndividualSport";
}

A more sophisticated option, but perhaps unnecessary for this use case, is to make these objects strongly typed:

public class SportType
{
    private readonly string _description;

    private SportType(string description)
    {
        _description = description;
    }

    public static readonly SportType TeamSport = new SportType("Team Sport");
    public static readonly SportType IndividualSport = new SportType("Individual Sport");

    public static implicit operator SportType(string s)
    {
        return new SportType(s);
    }

    public static implicit operator string(SportType s)
    {
        return s._description;
    }

    // equality overrides etc.
}

The advantage here is that you can use these values as strings

string sportType = SportType.TeamSport;

but you don't have to declare variables and parameters as bare strings:

public void SetFavoriteSportType(SportType sportType)

Again, these are just options; ultimately it comes down to how your application will be deployed and how subject these data are to modification.

1
unnknown On

I think the problem with the enum approach is when you have to add new SportTypes and MatchTypes. If your drop downs bound to those Enums then you would have to redeploy every time they change