Looking into Enum Support in Entity Framework 5.0 Code First
- by nikolaosk
In this post I will show you with a hands-on demo the enum support that is available in Visual Studio 2012, .Net Framework 4.5 and Entity Framework 5.0.
You can have a look at this post to learn about the support of multilple diagrams per model that exists in Entity Framework 5.0.
We will demonstrate this with a step by step example. I will use Visual Studio 2012 Ultimate. You can also use Visual Studio 2012 Express Edition.
Before I move on to the actual demo I must say that in EF 5.0 an enumeration can have the following types.
Byte
Int16
Int32
Int64
Sbyte
Obviously I cannot go into much detail on what EF is and what it does. I
will give again a short introduction.The .Net framework provides
support for Object Relational Mapping through EF. So EF is a an ORM tool
and it is now the main data access technology that microsoft works on. I
use it quite extensively in my projects. Through EF we have many things
out of the box provided for us. We have the automatic generation of SQL
code.It maps relational data to strongly types objects.All the changes
made to the objects in the memory are persisted in a transactional way
back to the data store.
You can find in this post
an example on how to use the Entity Framework to retrieve data from an
SQL Server Database using the "Database/Schema First" approach.
In this approach we make all the changes at the database level and then we update the model with those changes.
In this post you can see an example on how to use the "Model First" approach when working with ASP.Net and the Entity Framework. This model was firstly introduced in EF version 4.0 and we could start
with a blank model and then create a database from that model.When we
made changes to the model , we could recreate the database from the new
model.
You can search in my blog, because I have posted many posts regarding ASP.Net and EF.
I assume you have a working knowledge of C# and know a few things
about EF.
The Code First approach is the more code-centric than the
other two. Basically we write POCO classes and then we persist to a
database using something called DBContext.
Code First relies on DbContext. We create 2,3 classes (e.g Person,Product) with properties and then these classes interact with the DbContext class. We can create a new database based upon our POCOS classes and have
tables generated from those classes.We do not have an .edmx file in this
approach.By using this approach we can write much easier unit tests.
DbContext is a new context class and is smaller,lightweight wrapper for the main context class which is ObjectContext (Schema First and Model First). Let's begin building our sample application.
1) Launch Visual Studio. Create an ASP.Net Empty Web application. Choose an appropriate name for your application.
2) Add a web form, default.aspx page to the application.
3) Now we need to make sure the Entity Framework is included in our project. Go to Solution Explorer, right-click on the project name.Then select Manage NuGet Packages...In the Manage NuGet Packages dialog, select the Online tab and choose the EntityFramework package.Finally click Install.
Have a look at the picture below
4) Create a new folder. Name it CodeFirst .
5) Add a new item in your application, a class file. Name it Footballer.cs. This is going to be a simple POCO class.Place it in the CodeFirst folder.
The code follows
public class Footballer { public int FootballerID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public double Weight { get; set; } public double Height { get; set; } public DateTime JoinedTheClub { get; set; } public int Age { get; set; } public List<Training> Trainings { get; set; } public FootballPositions Positions { get; set; } }
Now I am going to define my enum values in the same class file, Footballer.cs public enum FootballPositions { Defender, Midfielder, Striker } 6) Now we need to create the Training class. Add a new class to your application and place it in the CodeFirst folder.The code for the class follows.
public class Training
{
public int TrainingID { get; set; }
public int TrainingDuration { get; set; }
public string TrainingLocation { get; set; }
}
7) Then we need to create a context class that inherits from DbContext.Add a new class to the CodeFirst folder.Name it FootballerDBContext.Now that we have the entity classes created, we must let the model know.I will have to use the DbSet<T> property.The code for this class follows
public class FootballerDBContext:DbContext
{
public DbSet<Footballer> Footballers { get; set; }
public DbSet<Training> Trainings { get; set; }
}
Do not forget to add (using System.Data.Entity;) in the beginning of the class file
8) We must take care of the connection string. It is very easy to create one in the web.config.It does not matter that we do not have a database yet.When we run the DbContext and query against it,it will use a connection string in the web.config and will create the database based on the classes.
In my case the connection string inside the web.config, looks like this
<connectionStrings>
<add name="CodeFirstDBContext"
connectionString="server=.\SqlExpress;integrated security=true;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
9) Now it is time to create Linq to Entities queries to retrieve data from the database . Add a new class to your application in the CodeFirst folder.Name the file DALfootballer.cs
We will create a simple public method to retrieve the footballers. The code for the class follows
public class DALfootballer
{
FootballerDBContext ctx = new FootballerDBContext();
public List<Footballer> GetFootballers()
{
var query = from player in ctx.Footballers where player.FirstName=="Jamie" select player;
return query.ToList();
}
}
10) Place a GridView control on the Default.aspx page and leave the default name.Add an ObjectDataSource control on the Default.aspx page and leave the default name. Set the DatasourceID
property of the GridView control to the ID of the ObjectDataSource control.(DataSourceID="ObjectDataSource1" ). Let's configure the ObjectDataSource control. Click on the smart tag item of the ObjectDataSource control and select Configure Data Source. In the Wizzard that pops up select the DALFootballer class and then in the next step choose the GetFootballers() method.Click Finish to complete the steps of the wizzard.
Build your application.
11) Let's create an Insert method in order to insert data into the tables.
I will create an Insert() method and for simplicity reasons I will place it in the Default.aspx.cs file.
private void Insert() { var footballers = new List<Footballer> { new Footballer { FirstName = "Steven",LastName="Gerrard", Height=1.85, Weight=85,Age=32, JoinedTheClub=DateTime.Parse("12/12/1999"),Positions=FootballPositions.Midfielder, Trainings = new List<Training> { new Training {TrainingDuration = 3, TrainingLocation="MelWood"}, new Training {TrainingDuration = 2, TrainingLocation="Anfield"}, new Training {TrainingDuration = 2, TrainingLocation="MelWood"}, } }, new Footballer { FirstName = "Jamie",LastName="Garragher", Height=1.89, Weight=89,Age=34, JoinedTheClub=DateTime.Parse("12/02/2000"),Positions=FootballPositions.Defender, Trainings = new List<Training> { new Training {TrainingDuration = 3, TrainingLocation="MelWood"}, new Training {TrainingDuration = 5, TrainingLocation="Anfield"}, new Training {TrainingDuration = 6, TrainingLocation="Anfield"}, } } }; footballers.ForEach(foot => ctx.Footballers.Add(foot)); ctx.SaveChanges(); } 12) In the Page_Load() event handling routine I called the Insert() method. protected void Page_Load(object sender, EventArgs e) { Insert(); } 13) Run your application and you will see that the following result,hopefully. You can see clearly that the data is returned along with the enum value. 14) You must have also a look at the database.Launch SSMS and see the database and its objects (data) created from EF Code First.Have a look at the picture below. Hopefully now you have seen the support that exists in EF 5.0 for enums.Hope it helps !!!