When I started into the world of .NET based web development, I often encountered the term “Entity Framework Code First” or “EF Code First”. Where as I could no where find the option to create “Code First” entities in the visual studio. 🙁 How disappointing! 😛 I could create ADO.NET Entity Data Model but that would create .edmx files which looked all cryptic to me! I was just beginning .NET and my background is heavily based on PHP and Python where nothing is “Visual”, we do it all in codes.
And then after going through some of the resources online, I finally understood what’s going on. The ADO.NET Entity framework has two popular approaches – “Database first” and “Code first”. As the names suggest, in the first approach you write your models, generate databases, map the database with your models etc. Here database comes first. On the other hand, in the “code first” approach, you write plain classes which are identical to your database objects. Then following specific convention, you magically map the defined classes with the database. No need to write (I mean generate) complex xml maps or all those mess.
While I agree that both the approach have their own benefits, strengths and all those positive things, I found the code first approach easier to get started as a novice. So how does it work? Let’s see!
Say, we already have a table defined somewhere. For convenience, let’s use the following SQL script to generate a table:
1 2 3 4 5 6 7 8 9 10 11 12 |
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Students]( [ID] [int] IDENTITY(1,1) NOT NULL, [Name] [text] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO |
I am not going to elaborate the process but the direction is to first create a database and then use the above sql codes to generate a table. It has one ID field that is auto incremented and the Name field. The simplest table structure I could think of! 😀
Now, in code first approach, convention is prioritized over configuration. Hence, we must define an identical class. Here it goes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//Students.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LearnMVC3.Models { public class Student { public virtual int ID { get; set; } public virtual string Name { get; set; } } } |
Remember those “virtual” identifiers are crucial. They have a lot to do with the magic that keeps things going. Another interesting thing to notice is that the Student object doesn’t derive from any other object.
Now, we need a database context. We shall define a class that will extend the “DbContext” class from the Entity Framework. The code should be like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//StudentsDb.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.Data.Entity.Infrastructure; namespace LearnMVC3.Models { public class StudentsDb : DbContext { public StudentsDb() : base("name=DatbaseConnection") { } public DbSet<Student> Students { get; set; } } } |
One thing to notice is that we must pass a database connection string to the DbContext class. In this case, I have a connection string defined in my configuration file and I am passing the name of the connection to the DbContext class.
With this, we’re ready to use the Entities we have generated. So, how do we use them? Let’s see some codes:
1 2 3 4 5 6 |
StudentsDb db = new StudentsDb(); Student st = new Student(); st.Name = "Masnun"; db.Students.Add(st); db.SaveChanges(); |
The above codes will insert a entry in the database when run. Give it a try! 🙂
PS: I am just beginning .NET and C#. If you have any comments, suggestions or plain feedback, please do feel free to leave in the comments. I would appreciate your contribution to my personal development 🙂
One reply on “Using Entity Framework: The CodeFirst Approach”
Thank`s for this post. This is very helpful for me.