Code First Approach in Entity Framework

In code first approach first we create classes (Code) and using this code database will be get generated. We need not use edmx file in code first approach. In code first approach code-first api is responsible to create and update database.

Create Code First Schema

Open visual studio and choose empty website. As we are not using edmx file so we have to add entity framework dll in our project. For that right click on the project and choose nugget packages.

code first approach

		Figure 1
		

Choose entity framework and install it in the application

add entity framework dll

		Figure 2
		

Now create the classes to map with the tables

public class employee
{
    [Key]
    public int emp_id { get; set; }
    public string name { get; set; }
    public int age { get; set; }

    public department dept_id { get; set; }
   
}

public class department
{
    [Key]
    public int dept_id { get; set; }
    public string dept_name { get; set; }

}
		

To give key attribute to the classes we have to use System.ComponentModel.DataAnnotations namespace.

As you can see in employee table I have created the relation as every employee is having department. When we will execute this code dept_id will be treated as foreign key in employee table.

Now create another repository class in which we have to inherit DbContext class and need to create DbSet properties to create entities.

public class efRepositary:DbContext
{
   public DbSet<employee> emps { get; set; }
    public DbSet<department> dept { get; set; }
}

		

Now go to the webconfig file and add connection string

<connectionStrings>
    <add name="efRepositary" providerName="System.Data.SqlClient" connectionString="Data Source=ISHA;Initial Catalog=ef_database;User ID=isha123;Password=******;Pooling=False"/>
  </connectionStrings>


		

Now go to your default page and add department in the department table.

efRepositary ef = new efRepositary();
        ef.dept.Add(new department() { dept_name = "HR" });
        ef.SaveChanges();
		

Note: - when table will be created the key column will automatically assign as identity column. So we need not to pass dept_id.

Now execute the application and check your database.

output of ef

		Figure 3
		

You can see three tables have been created. Departments and employees are our model table. Apart from these two tables you see the dbo_MigrationHistory is also there. It will maintain the model history for tables.

Note: - as you can see its give foreign key column not a suitable name. We can also change it but we will discuss it in later tutorial.


Email Address

For any query you can send mail at info@techaltum.com
Thanks