Yaron Levi
Yaron Levi

Reputation: 13077

Entity Framework 5 Enum that is built from a db table

I have those two entities :

enter image description here

Color entity is mapped to a table of constant values that represent colors.
Code=1, Name="Red"
Code=2, Name="Blue"
And so on...

In Car entity, the Color property is of type int and has a foreign key constraint to the Code property in Color entity. I want to convert the Color property in Car to an Enum, but the Enum should get it's values from Color table.

The Enum could be updated in each build action or an "update model" action in the designer. Can this functionality can be achieved ?

Upvotes: 1

Views: 2399

Answers (2)

Renier
Renier

Reputation: 540

For me the first question is why? I had a similar technical need but the business need was to help with reporting. Enums works great to make code simpler to read and maintain, but is you have to create a report in say SSRS then you don't have access to the enums (okay I am sure some advanced SSRS users will say you can link in assemblies etc, but that is not the point). We played a bit with a prebuild script (could also run post build) to generate inline scaler function scripts to execute against the db. This way you could do select statements such as:

SELECT Model, fColorNameEnum(Color) FROM Car

This way you do not have to touch you reports again if you add a new element in your enum. I tend to use enums in the implementation of business logic, typically item status or workflow state. Adding a new option thus require adding new logic which means doing it in code. If you are never going to reason over the color value in code, then what is the reason for wanting to put it in an enum rather than just another linked object?

Upvotes: 0

phil soady
phil soady

Reputation: 11348

" but the Enum should get it's values from Color table. "

So whats wrong with what you have? Anyway since you asked... An enum is by definition inside the assembly. So as soon as a new color is added to the table you have an outdated Enum. But if you are ok with having upto date at build time. There is a good option.

Clearly the suggestion to use T4 is interesting . But the t4 would need to connect to DB and read it. When T4 goes beyond source generation, it can be easier to use a simple app. Unless of course you are already good at t4. So if t4 is a little hard for this task try:

A simple side app, that reads the DB and updates the EnumColor.cs would be plausible.

IE a simple console app. Place as a pre build step. The pre-build reads the DB, rewrites the enum.cs file and the compile/build then follows.

enter image description here

**Easy Alternative: using a Dictionary which you can extend at runtime **

Dictionary<int,string> colors

Upvotes: 1

Related Questions