14

I have an order which has a status (which in code is an Enum). The question is how to persist this. I could:

  1. Persist the string in a field and then map back to enum on data retrieval.
  2. Persist this as an integer and then map back to enum on data retrieval.
  3. Create separate table for enum value and do a join on data retrieval.

Thoughts?

leora
  • 188,729
  • 360
  • 878
  • 1,366
  • A nice feature of #1 is that, if the DB does get out of sync with the app, at least you know what value you meant to store, and it would be easy to fix the DB if the string value of the enum was changed in .NET. – mbeckish Mar 23 '09 at 16:35

5 Answers5

8

If this is a fixed list (which it seems it is, or else you shouldn't store it as an enum), I wouldn't use #1.

The main reason to use #3 over #2 is for ease of use with self-service querying utilities. However, I'd actually go with a variant of #2: Store the value as an integer and map to an enum on data retrieval. However, also create a table representing the enum type, with the value as the PK and the name as another column. That way it's simple, quick, and efficient to use with your code, but also easy to get the logical value with self-service querying and other uses that don't use your data access code.

Jonathan Rupp
  • 15,522
  • 5
  • 45
  • 61
3

#3 is the most "proper" from a database/normalization standpoint. Your status is, in effect, a domain entity that's linked to the order entity.

Harper Shelby
  • 16,475
  • 2
  • 44
  • 51
0

hibernate uses integers by default. if your enum is not going to change very often, this is not a bad idea, i think.

PeterP
  • 4,502
  • 7
  • 22
  • 21
0

I'd use an integer mapped to value in another table with the values. You could also then map the enum to the same value, but then you'd have to update in both spots.

sfossen
  • 4,774
  • 24
  • 18
0

I suppose it depends on where the data will be retrieved. With #3, you could retrieve the data without relying on your .NET front end. But it is also possible for your database table to get out of sync with the enum code.

Option #2 is certainly the most efficient way to do it for storage... but storage is cheap.

Jeff Martin
  • 10,812
  • 7
  • 48
  • 74