开发者

Enums in NHibernate from Existing Table

开发者 https://www.devze.com 2023-01-28 21:52 出处:网络
I have many tables in my schema design (legacy, cannot be changed) with the pattern: Widget -----------

I have many tables in my schema design (legacy, cannot be changed) with the pattern:

Widget
-----------
WIDGET_ID (int, PK)
WIDGET_TYPE_ID (int, FK)

WidgetType
-----------
WIDGET_TYPE_ID (int, PK)
WIDGET_TYPE_NAME (varchar)

example Widget records:

WIDGET_ID | WIDGET_TYPE_ID (FK)
1           3
2           4

example WidgetType records:

WIDGET_TYPE_ID | WIDGET_TYPE_NAME 
3                "Foo"
4                "Bar"

Basically many tables in my DB have corresponding "Type" tables associated with them that I would like to construct as enumerations in the object model, ie:

Widget newWidget = new Widget();
newWidget.WidgetType = WidgetType.Foo;

Is there ANY way to do this with NHibernate, if so what would the mapping look like? If not, what's the best approximation? The only way I could think of was to construct a (not persisted) enumeration type in code that matches the type IDs:

enum WidgetType { Foo=3, Bar=4 };

But I'd rather开发者_如何学Go not have to maintain this enum as things are added/removed from the DB...


C# enumerations are just a design-time convenience that exist to make code easier to read and write. They just compile to integers (or whatever the appropriate primitive type is).

To get NHibernate (or any other ORM) to manage them, you'd have to integrate it into the IDE and Visual Studio would have to interact with it while you edit your code. That might be useful, but I suspect you'd have to have a lot of enums that change fairly frequently for it to really be worth it.

There's no add-in like that for NHibernate that I'm aware of, but you can use a code generator to keep your enumerations in sync with your database tables (for example, the Text Template Transformation Toolkit - aka "T4 Templates" - which comes with Visual Studio).

0

精彩评论

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

关注公众号