简体   繁体   中英

Correct way to use a database for state

I would like to track some work using a database, using tables like State and Status . Each Status table has an FK to State . A valid status may be something like 'transferring', and it's state may be 'active' or 'completed'. There would be a third table (maybe StatusEvent ). I'm using Entity Framework 6.0 to map to the database.

One thing I'm trying to figure out is how to properly represent those states and statuses in my C# code. For example, there may be the following states:

StateId    Name
1          active
2          complete
3          error

In my code, I want to set the state on a status to 'active'. I could find the StateId that matches the text 'active' and then use that. Maybe make it a bit safer with ToLower() or something. I could also keep a list of state ids. Something like const int Active = 1 . But then I need to make sure nothing really changes in the db...

At the end, I want to be able to call a method like SetStateOnStatus(int statusId, State state) .

I looked into the Enum stuff from entity framework- doesn't seem too useful actually as the state descriptions are just in code, and the db just contains an int. I need to have those descriptions in another table so I can query the database later. Maybe I'm missing something here?

So what is the right way to do this?

As Robert mentioned, it is good to use look up tables. You can create valid_status and valid_state table where you can fill up your user-defined values as you mentioned. Whenever you are inserting status, get it from the status table. Similar way you can get stateid instead of passing as hard coded value.

Do you really need the State table? If the values in state are going to be fixed, then you can create an enum like you suggested in the code. (Integers mapped to them will do - public enum State {Active (1), ..;} ) This will save you time such that you dont have to make a database call.

You can create Status Table but instead of having a foreign key to State, you can have a State column. That will contain the int value retrieved from the enum.

When you call setStateOnStatus(..) you can make a database call, save the information there.

If the values in State are going to change often, then I guess it will make sense to have the State table

So I won't mark this as the answer, as I don't know if it was the best way. But what I ended up doing was using a t4 template using something similar to this (but not exactly like that) to generate enums when I save/run the template generation. I then used those enums for my method call.

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