Friday, June 27, 2014

Step by Step : Entity Framework Code First approach


Hi,

I hope you are enjoying my posts. I am here with my next post which deals into the steps that we need to follow in order to create and work with database using Entity Framework Code First approach. This is not by any means the complete and exhaustive post on Entity Framework Code First, but this post can be used as your typical first Hello World program for Entity Framework Code First approach.

As I always say, this is just one of the way which I followed in my projects. I am not saying this is the best and it doesnot have cons. My main intension is to share my experience so that it will be useful for the needy. I am new to blogging and I tried to make this post as much interesting as possible. Please excuse me for my grammatical errors and typos. I welcome your constructive comments and suggestions which helps in improving this post and my technical skills.

 As per Entity Framework team, Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

Code First approach
was introduced in Entity Framework 4.1 where you can focus on creating classes as per domain requirement and Code First API will create the database on the fly based on your entity classes and configuration rather than concentrating on designing your database first and then create the classes which matches your database design.

 
 For this article, I am using the following tools/technologies
Visual Studio 2013
EntityFramework 6.1
C#
.NET Framework 4.5
SQL Server 2008 R2
Windows Server 2008 R2

I always have the habit of creating empty solution first and then work on it. Here also I did same thing. I created a folder called "SignalR" in "D\XXXX\My Programs" folder and created an empty visual studio solution titled "EFCodeFirstDemo"

Add a new C# class library called "DomainClasses" and add below two classes

 public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public virtual Blog Blog { get; set; }
    }


 public class Blog
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string BloggerName { get; set; }
        public List<Post> Posts { get; set; }

        public string BlogCode
        {
            get { return Title.Substring(0, 1) + " : " + BloggerName.Substring(0, 1); }
        }

       public Blog()
        {
            Posts = new List<Post>();
        }
    }


 

We need a mechanism by which we can interact with database, and Entity Framework provides this in form of DbContext. Now, lets use this DbContext and develop our way of interacting with database. For this add new C# Class Library project called "DataAccessLayer" and add reference of DomainClasses to it.

Now we need to add Entity Framework to DataAccessLayer project which can be done either by using NuGet or Package Manager Console. Lets see one by one

1) Manage NuGet Packages : Right on DataAccess and click Manage Nuget Package as shown in below screen shot.

 




This will open Manage Nuget packages dialog. Search for Entity Framework and install "EntityFramework" as shown in below screen shot which brings everything need to run it on IIS and ASP.NET



2) Package Manager Console :  Open Package Manager Console. Please see below for its location



Type following command in Package Manager Console after making sure that you select DataAccessLayer project under Default project

Install-Package EntityFramework




Now add new class called Context.cs in DataAccessLayer project and add below code

using System.Data.Entity;
using DomainClasses;

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


      
       public Context() : base("Data Source=myserver;Initial Catalog=test;Integrated Security=True")
        {
           
        }
    }
}


Now it's time to create a mechanism by which we can call our Context class so that we can create database, tables, and add data into those tables. 

For this let's add a new ConsoleApplication and add references to DataAccessLayer and DomainClasses and do below steps
1) Add EntityFramework like above ( the way we added to DataAcessLayer)
2) Add below code for Program.cs
  
using DomainClasses;
using DataAccessLayer;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Started");
            CreateBlog();
            Console.WriteLine("Created");
            Console.ReadLine();

        }

        private static void CreateBlog()
        {
            var blog = new Blog { BloggerName = "Winzikha", Title = "EntityFramework 6.1 Blog"};
            var dbContext = new Context();
            dbContext.Blogs.Add(blog);
            dbContext.SaveChanges();
        }
    }
}





That's it, now run Console application.

Now lets see briefly what happened.

If you see constructor of Context class you will see that below connectionstring

Data Source=myserver;Initial Catalog=test;Integrated Security=True

As soon as you instantiate context

var dbContext = new Context();  the DbContext will look into Blog.cs and Post.cs of DomainClasses to understand the structure and creates the tables Blogs and Posts in myserver inside test database. 

The automatic primary keys will be created for Blogs and Posts table  taking into convention that Id properties in our Blog.cs and Post.cs are primary keys.Posts table also has Blog_id foreign key. DataContext will create this for us.It determined that there must be a relationship between Blogs and Posts tables so it build foreign key. 

The above all will be done by Code first by default.




Note: If you don't give the connection string for your DbContext class, it will take below connection string by default for EF 6.1. In this case you need open your (localdb)\v11.0 to see new tables. It will take the namespace of our Context class ( in our case DataAccessLayer.Context) as name for our database.

Data Source=(localdb)\v11.0;Initial Catalog=DataAccessLayer.Context;Integrated Security=True;MultipleActiveResultSets=True

Please see below for the code on how to add Posts to a Blog

private static void AddPost()
        {
            var db = new Context();
            var blog = db.Blogs.Find(1);
            blog.Posts.Add(new Post{Title = "My First Post", Content = "Simple Post"});
            db.SaveChanges();
        }


The above will insert a record into Post table with Id=1 and Entity Framework will automatically insert Blog_Id = 1 ( Foreign Key).


Conclusion :
In this article we learned how we can create a database, tables using Entity Framework Code First approach. We also saw how we can insert data into tables. We saw that we just created normal C# classes ( Blog and Post) without any idea about our database and designing our database and simple Context class which inherits from DbContext class will actually create tables, columns, and all constraints for us. We also saw what happens when we donot specify connection string to  Context class.


I hope you enjoyed reading this post as much as I did while writing it. Please feel free to let me know your valuable and constructive comments and suggestions which can help me to make this article better and improve my technical and written skills. Last but not the least please excuse me for my grammar and typos.

Thanks and have a nice and wonderful day.