Entity Framework – Code First Approach Example


In this article, Let’s see an example of Entity Framework – Code First approach

If you don’t know about Entity Framework, please go through this article.

Just to revise, In the Code First approach, You write your classes first and then create database from these classes.

Entity Framework – Code First Approach Example

1. Let’s create a console application. Name it as “EFCodeFirstExample”.

2. Since it’s Entity Framework project, let’s add reference to “Entity Framework” assembly via nuget package manager.

There are many ways to do it. We can add it by right clicking the project and selecting the “Manage Nuget Packages” menu. A window will appear, select “Online” from left hand side and enter “EntityFramework” on top right hand side, press enter to search. Entity Framework package will appear in search result, press “Install” to continue.

3. Once done, you can see from the project references that the reference to “EntityFramework” is added.

Also we need to add a namespace reference to Entity framework.


using System.Data.Entity;

4. Let’s start with coding part. We will create 2 simple classes (POCO) to understand the code first approach namely “Blog” and “Post”.

Consider following Blog class.


public class Blog
{
[Key]
public int IDBlog { get; set; }
public string Name { get; set; }
public virtual List<Post> Posts { get; set; }
}

5. Consider following Post class


public class Post
{
[Key]
public int IDPost { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int IDBlog { get; set; }
public virtual Blog Blog { get; set; }
}

6. We have specified Key attribute to “IDBlog” and “IDPost”, which means both are primary keys for respective tables (Tables are created once we run the application).

Virtual properties (virtual List<Post> Posts and virtual Blog Blog) are marked for lazy loading, which means when we try to access them, entity framework will load the associated data. Those are called navigation properties, which means they will create foreign key constraints in the DB.

7. Let’s create a context class now. Consider following BloggingContext class.


public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}

Here please note that our BloggingContext class is derived from the “DbContext” class.

8. Now let’s write our main program where we will add a new blog and list the blogs in the DB.


class Program
{
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
// Create and save a new Blog
Console.WriteLine("Please enter blog name:");
string blogName = Console.ReadLine();

Blog blog = new Blog();
blog.Name = blogName;
db.Blogs.Add(blog);
db.SaveChanges();

// List all available blogs in the DB
Console.WriteLine("All blogs in the DB:");
foreach (var item in db.Blogs.ToList())
{
Console.WriteLine(item.Name);
}
Console.ReadLine();
}
}
}

9. Now you will think about connection string to DB. We did not mention about DB and connection string in the project. By default, visual studio 2012+ has local DB.

By convention DbContext has created a database for you.

1. If a local SQL Express instance is available (installed by default with Visual Studio 2010) then Code First has created the database on that instance

2. If SQL Express isn’t available then Code First will try and use LocalDb (installed by default with Visual Studio 2012+)
10. The database is named after the fully qualified name of the derived context, in our case that is EFCodeFirstExample.BloggingContext.

11. Once you run the application, it will create the DB for us upon our defined POCO classes. Here is the output for our application.

12. Now if we need to change the table schema, then what? In such case, we need to change out classes which in turn update our DB. To do this we have a feature in Entity Framework called Code First Migrations, or Migrations.

13. Consider following change in out blog class.


public class Blog
{
[Key]
public int IDBlog { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
public virtual List<Post> Posts { get; set; }
}

14. To update this change in our DB, we need to enable Code First Migrations for our BloggingContext. Open the “Package Manager Console” from the solution and run the command. Enable-Migrations

15. This command will add 2 files in the project named “Configuration.cs” (This file contains the settings that Migrations will use for migrating BloggingContext) and “201310141156476_InitialCreate.cs” (it represents the changes that have already been applied to the database).

16. Now let’s run the command Add-Migration AddDateCreated command in Package Manager Console to update out DB for new changes. It will create a file called “201310141332176_AddDateCreated.cs”


public partial class AddDateCreated : DbMigration
{
public override void Up()
{
AddColumn("dbo.Blogs", "DateCreated", c => c.DateTime(nullable: false));
}

public override void Down()
{
DropColumn("dbo.Blogs", "DateCreated");
}
}

17. Run the Update-Database command in Package Manager Console. This command will apply any pending migrations to the database. You can use the –Verbose switch when calling Update-Database to see the SQL that is being executed against the database.

18 And you will see the DateCreated column is added in our DB.

Hope this helps. Please comment below the post if you have any doubts or questions.

Source Code Download:

Github [Repository Link]

Advertisements

2 thoughts on “Entity Framework – Code First Approach Example

  1. Pingback: Entity Framework – Model First Approach Example | A Programming Blog

  2. Pingback: Entity Framework – Database First Approach Example | A Programming Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s