0

I have a project using Entityframework Code First. And the model contains a few enums which I want to generate from the database using the T4 text template.

But I'm facing a few challenges:

  • If the database doesn't exist yet, no enums will be generated;
  • If the database does exists, how to run the T4 template?
  • And how do I get the enums in the database before running the T4 template?

Has anyone done this before and overcome these challenges?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Quoter
  • 4,236
  • 13
  • 47
  • 69
  • which version of Entity Framework are you using? EF 5 and later have built in support for enum data types without the need of T4. – Claies Oct 25 '14 at 22:06
  • I have the latest stable version, 6.1.2 IIRC. But what you said is true, but I need them as lookup tables in the database too. – Quoter Oct 25 '14 at 22:15
  • see also http://stackoverflow.com/q/11167665/10245 – Tim Abell Jun 01 '16 at 15:23

1 Answers1

2

There is a NUGET package which handles the case that you are trying to solve, ef-enum-to-lookup. Documentation.

Run EnumToLookup.Apply() from your Seed method in either your database initializer or your EF Migrations.

This package creates lookup tables and foreign key constraints based on the enums used in your model. Unlike the default Entity Framework support, you do not need to create a DBSet<T> for your enum classes, which maps enum values to int.

Claies
  • 22,124
  • 4
  • 53
  • 77
  • 1
    Damn that looks great! Does it handle a collection of enums too? I have looked at the sample project, I didn't see any collection of enums at all in an entity class. – Quoter Oct 26 '14 at 21:45
  • 1
    in my experience, it handles any enum that is referenced by an entity object, either directly or through collections. however, you will definitely want to verify the schema that gets generated. – Claies Oct 26 '14 at 22:57
  • Cheers for the recommendation @Claies :-) – Tim Abell Jun 01 '16 at 15:24