开发者

C# Enum using values in Sql Server table

At the moment I have a SQL Server 2005 table that looks a bit like:

ID | name  | desc
---------------------开发者_StackOverflow社区-
1  | ONE   | Value One
3  | THREE | Value Three
5  | FIVE  | Value Five

This table corresponds with an enum in C# that looks like:

enum MsgTypes{
  <summary>Value One</summary>
  ONE = 1,
  <summary>Value Three</summary>
  THREE = 3,
  <summary>Value Five</summary>
  FIVE = 5
}

So my question is this: Is there a good way to associate the enum to the SQL table so that any changes/additions to the values in the table don't need to be manually made in the c# code?


If you want it to be somewhat dynamic, why make it an enum to start with? Just fetch the details from the table on app startup, and remember them in (say) a Dictionary<int, string>. You could always encapsulate the value within your own value type which enforced the range, if you wanted to.

Alternatively, if you don't mind recompiling, you could fetch it at build time and autogenerate the enum source code.


I had to have a think about something similar recently (refactoring an enum) -- basically I considered using a Dictionary<A, B> to store the enum values in. You could dynamically load from the table to populate the dictionary if you wanted to.

One thing I'd add -- is if you're replacing an enum that already exists with something dynamic you'll have to think about what you're going to do with exceptions raised as part of populating it dynamically.


To me it depends on how often the enums/DB lookup tables change. We have about a half dozen enum/lookups like this in our system, and i don't mind recompiling to add an emum option + DB row becuase:

  1. It doesn't happen very often - probably twice in the past year that i can think of
  2. There is usually new business logic surrounding the new option so coding is necessary anyway.


Another alternative would to implement a custom object with ID, Name, and Desc properties that would encapsulate the database table.


I accept with what Jon is suggesting, but then if you prefer to have your Enum list in the DB and want to use them in your code, you could use TypeTable feature from nHydrate for your project.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜