简体   繁体   中英

Creating an enum/class from a Database Table

I have a database table that essentially contains different types of things. I'll use animals as an example. I have a table called AnimalTypes:

AnimalTypes
{
     ID:int,
     Name:string
}

I then populate it with:

1:Dog,
2:Cat,
3:Fish

I would like to then have some sort of C# object created that functions similar to this enum be entirely read from the database:

enum AnimalTypes
{
     Dog = 1,
     Cat = 2,
     Fish = 3
}

Is there a way to create an enum/class from a database table as described? I basically want to be able to reference things in the AnimalTypes table using intellisense and AnimalTypes.Dog as an example; I don't actually need an enum, just something that kind of functions like one. Is this possible?

Edit: I'm not really that thrilled about generating a DLL as I've seen in other related problems. I feel like this should be possible with reflection.

Lets suppose I don't need intellisense.

Try this solution:

using T4 code generation for lookup tables.

You will have to generate an assembly if you want to be able to use the enumeration or class at compilation time. Reflection happens at execution time so that won't give you intellisense.

This is a common problem - there are a set of distinct values in a database table and those values don't change often so they are modeled as an enum in the source code. This allows these somewhat static values to be easily used in a very readable way. The problem is that when the values do change, it would be nice if the enum changed as well.

The problem with trying to keep the enum and database in sync is that an automatic process doesn't change the fact that if you are changing the database it would be very unlikely that you would do so without having to roll new code to leverage the changed value. It is better to model these values as an enum and still store them in the database. Just manually sync them as the need arises.

总有代码生成: http//www.mygenerationsoftware.com/如果你不想去反射路线。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM