开发者

Handle database look-up values in ASP.NET application

开发者 https://www.devze.com 2022-12-17 02:15 出处:网络
Almost all the applications I worked on involve some look-up values. For example, a lot of times a list of languages ( English, French, etc...) need to be displayed on the WebForm for user to choose.

Almost all the applications I worked on involve some look-up values. For example, a lot of times a list of languages ( English, French, etc...) need to be displayed on the WebForm for user to choose.

The common data structure for such look up values include an integer Id and a string as name. Since these look-up values are used so frequently, and they are unlikely to be changed. Most of time, instead of grabbing them from database, I just define a global enum in C# like this

enum Language : int { English = 1, French = 2}

I've been handling look-up values like this for years now. I knew it may not be the best way to handle them. For example, every time a new language is added to the system, somebody needs to remember to update that enum.

I guess this is a very common scenario,开发者_运维问答 just wondering how you guys handle this type of look-up values.

Thanks,


I usually put them int he database anyway, because you never know if and when they'll need to change. There have been times when - by design - I know that the list will not change, and for those, I will use enums instead. All other cases, I will use a database table.


Depending on the data requirements, I typically handle small lookups like that in a configuration file often loaded singularly to be applied as an application variable for all instances of the app. The data is looked up once when the application is started or recycled and then remains useful until it is dead.

Although, I have a lot of intermediate data of similar nature that requires regular maintenance. It is easier to put this into a database because at least then you can build a small maintenance application to handle it. If you put them in an enum, you have to recompile and redeploy.

I ran into a similar issue with resource files. Since resource files are compiled, they require another redeployment.


You may benefit from T4 Templates. I haven't used these yet because we haven't had a requirement to meet the need, but I'd like to use them eventually.

Here's a great article for generating enums from a database table (the code is hard to read on the page, there is a link to the source at the end of the article): http://www.thecodejunkie.com/2008/11/generate-enums-from-database-using-text.html

Also, Scott Hanselman has a list of great T4 templates/articles on his blog.

T4 Templates on MSDN

0

精彩评论

暂无评论...
验证码 换一张
取 消