简体   繁体   中英

database lookup table to enum or similar

I am using lookup tables for references. eg registration types, admin, moderator then using a factory to determine the type of registration. What is the easiest way to create a strongly typed way of comparing registrations. Sort of a similar behaviour to an enum. for example

pssudo code

class regfactory
{
    case()        
        if(regType.Admin: return new adminReg()      
}

The only way I can think of is a dictionary of magic strings generated from the database.

I bevieve the only way to to accomplish strongly typed enums for your situation would be code code generation. Anything not generated before compiletime would not serve for strong typing.

Robert Koritnik posted a very slick way to do this: T4 template to Generate Enums

Another way to 'generate' better readable enum names (in case you need them) is the HUmanizer project at https://github.com/MehdiK/Humanizer .

From a practical point of view it may seem a bit error-prone and you may feel like you're breaking some good practice rule by not centralizing access to that data and leaving it at risk of going out of synch during maintenance, however, from an architectural point of view, considering that we're talking about look-up data, it's ok to hard-code it as it's just part of your "static data contract", if you will.

If you do have lots of those, then maybe there could be a case for putting those constants in a format where a build or database patch script could update them when those values are changed, but 9 out of 10 just stuffing them in an enum works fine.

It's worth noting that some ORMs do have good support for enums, including EF which will allow for keeping those values in synch if you adopt a code first approach. However, we're talking about adding a whole new layer to your software so you gotta have more reasons than just wanting to keep your static look-up data in synch to implement that.

You can use reflection in c# . There is an excellent example on this answer to list the declared classes in a given namespace.

Then you would compare the name of your registration type with the available classes' names to decide which class to instantiate.

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