0

I have metadata in a DB table that i want to use in code. The metadata is different sorts of Time types for reporting spent time.

The data can be: NormalTime OverTime Vacation Illness etc

The data have a ID and a description and some other stuff.

ID = 1
Name = "Regular time"
Description = "Normal work time"

What is a good way to relate to this data in my code?

If for example i want create a method that sums all the NormalTime reported (i have another table that stores used time where the NormalTime ID and amount and some other stuff) how do i do that?

I dont want to hardcode the ID:

Select * from xyz where TimeType = 1

What i wanna do is:

Select * from xyz where TimeType = NormalTime.

Otherwise the code becomes very hard to read.

In my current solution i have hardcoded string consts that correlates to the ID. The problem with this is if someone changes the description of the TimeType from NormalTime to something eles the hardcoded string const sais one thing and the db data sais something else. And yes, this has happend as i dont have control over the DB content :(

So, how do I solve this in the best maintainable and readable way where changes can occur in the DB table and the code dont get very hard to read. Where someone can add TimeTypes to the DB and later I can add methods that uses them in code.

merger
  • 698
  • 1
  • 10
  • 28

2 Answers2

2

One way to do this would be to use Visual Studio's T4 text generation templates. (Entity Framework uses these for its code generation)

You can create a template file which contains code to pull the tables with metadata from the database, and generates classes with static constants in.

They do need to be run whenever the database changes, though. But I think you might be able to set them up so they do re-generate every time your code is built.

A question about T4 templates

Community
  • 1
  • 1
Daniel Neal
  • 4,165
  • 2
  • 20
  • 34
1

You could have an enum type on the C# side that maps to a table in the database.

http://www.codeproject.com/Articles/41746/Mapping-NET-Enumerations-to-the-Database

guillaume31
  • 13,738
  • 1
  • 32
  • 51