Creating an enum / class from a database table

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

AnimalTypes { ID:int, Name:string } 

Then I fill it as follows:

 1:Dog, 2:Cat, 3:Fish 

I would like for you to have some kind of C # object that functions like this listing should be fully 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 really don't need an enumeration, just something like such functions. Is it possible?

Edit: I'm not really worried about creating a DLL, as I saw in other related issues. I feel this should be possible with reflection.

Suppose I do not need intellisense.

+4
source share
3 answers

You will need to generate the assembly if you want to be able to use an enumeration or class at compile time. Reflection occurs at run time, so it will not give you intellisense.

This is a common problem - there is a set of different values ​​in the database table, and these values ​​do not change often, so they are modeled as enum in the source code. This makes it easy to use these few static values ​​in a very readable way. The problem is that when values ​​change, it would be nice if enum also changed.

The problem with trying to maintain the synchronization of enum and the database is that the automatic process does not change the fact that if you change the database, it would be very unlikely that you would do this without having to run new code to use the changed value. It is better to model these values ​​as enum and store them in a database. Just manually sync them as needed.

+2
source

Try this solution:

using T4 code generation for lookup tables.

+3
source

Always code generation: http://www.mygenerationsoftware.com/ if you do not want to follow the reflection route.

0
source

Source: https://habr.com/ru/post/1332998/


All Articles