Enum Support (EF Designer) in Entity Framework 5
Entity
Framework 5 brings number of improvements and Enum Support in EF Designer or Code First is one of them. In this
post you will learn it by creating a simple console application then will add
EF Designer and will sketch the Model on designer surface. Please note, EF
Designer can also be used with the Database First workflow to map to an existing
database.
Just
follow the steps, to setup the demo project.
Step 1: Create New Project
Create
a new console application File > New > Project > Visual C# >
Console Application.
Step 2: Adding EF Designer (ADO.NET
Entity Data Model)
Right
click on the project name in ‘Solution Explorer’, point to ‘Add’, and then
click ‘New Item’ and in the window select ‘Visual C# Items > and then Data’,
now you will find ‘ADO.NET Entity Data Model’ in the Templates pane, add it in
the project.
ADO.NET
Entity Data Model will bring following things:
EnumTestModel.edmx
file that defines the conceptual model, the storage model, and the mapping
between them. Sets the Metadata Artifact Processing property of the .edmx file
to Embed in Output Assembly so the generated metadata files get embedded into
the assembly.
Assemblies
files like EntityFramework, System.ComponentModel.DataAnnotations, and
System.Data.Entity.
EnumTestModel.tt
and EnumTestModel.Context.tt files and adds them under the .edmx file. These T4
template files generate the code that defines the DbContext derived type and
POCO types that map to the entities in the .edmx model.
Step 3: Adding New Entity
Right
click on Designer and select Add New > Scalar Property. This will bring
following window, enter the name ‘Student’ in Entity name box and it will
pluralize the Entity Set name (like Students) automatically.
Step 4: Adding Scalar Property
Add
‘Name’ and ‘Course’ scalar properties and make sure to change the ‘Type’
property of ‘Course’ scalar to ‘Int32’. As you know, EF5 enumeration can have
the following underlying types only:
Byte, Int16, Int32, Int64 or SByte.
Step 5: Create Enum
Now,
right click on ‘Course’ property and click on ‘Convert to Enum’.
In
the dialog box use ‘CourseEnum’ in ‘Enum type Name’ and add members and click
on OK button.
Step 6: Check Enum in Explorer
Open
the Solution Explorer and expand ‘Model1.tt > Courses’, you can also check
it from ‘Model Browser’.
Step 7: Data Handling
Now,
I all set to retrieve data and for this we need some code in Main() method.
Step 8: Find Database
When
you run the application the first time, the Entity Framework creates a database
for you. Because we have Visual Studio 2012 installed, the database will be
created on the LocalDB instance. By default, the Entity Framework names the
database after the fully qualified name of the derived context.
I
hope you like it. Thanks.
Comments
Post a Comment