Sunday, July 6, 2014

Code first approach in Entity Framework using Data Annotation and Fluent API

I am planning to cover few important features of Entity Framework by few series of articles followed by this. I hope, it will help from novice to experience .NET developer.

I will expect you are already familiar with the term “Entity Framework” and want to know few more about it. Then you are in right place. Yes, entity framework is Microsoft’s ORM (Object relational mapper) , I said, It’s Microsoft’s product because there are many similar product in same row from other vendor. NHybernate is one of them, which serves similar flavor.

Let’s understand the term “Object relational Mapper”. Here, object is nothing but our class and relation is representing the tables which has stored in Database. Now, in previous days developers used to write code manually to fetch data and convert the data to domain object and then pass the object across layers.  Then industry started thinking to make developer’s life easy. They started to automate the mapping process by some framework which can able to create class automatically from the databas , or can able to replicate the table as a class.

So, in short , this is the purpose behind use of Entity Framework, It can automatically generate model code , takes care of SQL query and make developer’s life easy. Even if you are less familiar with Database part, Entity Framework will take care to you.

Let’s come in next discussion, How we can use Entity Framework in our application? There are three approaches to implement Entity Framework in application. We will discuss those for better understanding of next articles in this series.

Code first approach
As the name suggest, in this approach we will write code at first to generate database and in one good day we will run those codes to see database in DB server. Here is few possible scenario where we can implement Code first approach.
·         You are hard code developer, always like to kidding with code, then code first approach is fit for you.
·         If you want full control over your database design without much knowledge of SQL and DBA.
·       If the application is brand new and is there is no existing database for that application
So, if any one of them happens with you, you are free to go with code first approach. Truth to be told, this approach is one of the popular approach among the three and from my personal experience, I have seen many brand new projects which has adapted this approach.

Database first
This is the next popular to code first approach. Database first approach fits best when database is created already, anyway here are few more possibilities.
·         When database is already exists, just need to develop application.
·         When the database structure is very complex and need to involve DBA professional.
·         When you are interested to work both coding and DB part of your application.
·         If you want additional features in POCO entities you must either T4 modify template or use partial classes.
·         Manual changes in Database are very easy in this approach, because it’s not directly dependent on code. Change Database, update model, works smoothly.
So, those are the scenario where database first approaches fit for.

Model First
 My personal experience says, this is less popular compare to code first and database first, the reason might be, developer don’t want to play the role of designer. Again, here are few possible scenarios when people should choose model first approach.

·         When you want to create data mode at first and share with other non-technical people.  By seeing code and table a non technical person may not understand but she might understand colorful representation of entity.
·         When your application is brand new and you are not bothering about lots of auto generate code, and you know where to tweak, if something goes wrong.
Anyway, the advantage is that, once you design the model, it will create your both class and database.
Ok, so we have understood various workflows of Entity Framework and in which scenario they fit with. Now, in this article we will discuss code first approach with example, and in consecutive article we will go dipper of Entity Framework.
Point to mention, there are two ways to go with code first approach

  1. Data annotation
  2. Fluent API

Both are popular and useful, but choice is yours. Anyway , here I will show code first approach in both ways.
So, create one brand new application, I have chosen console application for demonstration, you are free to choose anything.

Code first approach using Data Annotation
Create one .cs file and give name person.cs and paste below code into it. As this his data annotation approaches, don’t forget to add System.ComponentModel.DataAnnotation namespace.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class Person
    {
        [Key]
        public int Id{get;set;}
        [Required]
        public string name { get; set; }
        [Required]
        public string surname { get; set; }
    }

    public class Address
    {
        [Key]
        public int personAdressId { get; set; }
        public string address { get; set; }

        [MaxLength(6)]
        public string pin { get; set; }

        [ForeignKey("Person")]
        public int PersonId { get; set; }

        //Navigation property
        public virtual Person Person { get; set; }
    }

    public class personContext : DbContext
    {
        public personContext()
            : base("DBConnectionString")
        {
            //If model change, It will re-create new database.
            Database.SetInitializer<personContext>(new DropCreateDatabaseIfModelChanges<personContext>());
        }
        public DbSet<Person> person { get; set; }
        public DbSet<Address> Address { get; set; }
    }
}

If you  are familiar with data annotation in MVC, then I hope ,you are well known with those attributes.  The Key attribute presenting primary key of the table (We will create table by running this script shortly)
The Person and Address class are very easy to understand. Just keep in mind that we have set foreign key property in Address class, which will point to primary key of Person class.
Now, let’s discuss the context creation part, Have a look on personContext class definition.  We have inherited it from DbContext class, in constructor we are passing “DBConnectionString” which we will define shortly in web.config file.
Within constructor, we are specifying that, let create database from scratch, If my model change. Here is the code

Database.SetInitializer<personContext>(new DropCreateDatabaseIfModelChanges<personContext>());

Now, we will specify connection string in web.config file in application. Here is code for mine.

<connectionStrings>
    <add name="DBConnectionString"
        connectionString="Data Source=SOURAV-PC;Initial Catalog=personDB;Integrated Security=true"
        providerName="System.Data.SqlClient"/>
         
  </connectionStrings>

The connection string is very simple. I don’t have included username and password, since I want windows authentication to be done, In need you can provide DB credential.
Please notice that , I have provided Database name as “personDB” , means when my code will create database, I am expecting that name as database name.
Fine, we have finished our necessary setup. Now we will run the code to seed database, Just modify the Main() function as below, If you are using console application like me.

public static void Main(string[] args)
        {
            using (var ctx = new personContext())
            {
                ctx.Database.Create();
            }
        }


Now, let’s run the application and wait for magic. Once it run without exception (Hopefully) just checks your database. Here is mine.


You will see the above database structure, where two tables will create associate with all keys. So, this is the data annotation approach to create database using code first approach of entity framework.
Now, we will implement same model to create database using fluent API. Have a look on below modified 
code of person.cs file.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class Person
    {
        public int Id{get;set;}

        public string name { get; set; }
        public string surname { get; set; }
    }

    public class Address
    {
        public int personAdressId { get; set; }
        public string address { get; set; }
        public string pin { get; set; }
        public int PersonId { get; set; }
        public virtual Person Person { get; set; }
    }

    public class personContext : DbContext
    {
        public personContext()
            : base("DBConnectionString")
        {
            //If model change, It will re-create new database.
            Database.SetInitializer<personContext>(new DropCreateDatabaseIfModelChanges<personContext>());
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Set primary key to Person table
            modelBuilder.Entity<Person>().HasKey(m => m.Id).Property(m => m.Id).IsRequired();
            //name fleld is required

            modelBuilder.Entity<Person>().Property(p => p.name).IsRequired();
            //surname is required
            modelBuilder.Entity<Person>().Property(p => p.surname).IsRequired();

            //set primary key to Address table
            modelBuilder.Entity<Address>().HasKey(m => m.personAdressId);

            //set max lenght property to 6
            modelBuilder.Entity<Address>().Property(m => m.pin).HasMaxLength(6);

            //Set foreign key peoperty
            modelBuilder.Entity<Address>().HasRequired(t => t.Person)
                .WithMany().HasForeignKey(t => t.PersonId);

        }


        public DbSet<Person> person { get; set; }
        public DbSet<Address> Address { get; set; }
    }
}

Code in Main() function will remain unchanged  and once we run the application ,we will get same database structure.

Border line:
As, this is the first article of this series, I have discussed few basic concepts and example, in coming article we will focus on various topics of code first approach.

No comments:

Post a Comment