Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Code First Approach in .Net

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 4
    • 0
    • 771
    Comment on it

    Hi Friends,

    Today I will tell you about using Code First approach using entity framework. There are some situations where you need to create the table(when it does not exist in the database). So to do this we will 
    use entity framework 6.0.0.0

    To do this i will use simple approach so that it will be easy to understand what a Code First approach is ? I will create a Console application so that it will easy to understood.
    Firstly Open a new project by opening the visual studio -> File -> New -> Project

    Under Templates select Windows then select the console application as shown in below figure :-

     

    Then you need to install entity framework from package manager console.

    Firstly Click on Tools from the top menu. Then go to "NuGet Package Manager" then click on "Package Manager Console".

    A window will be open as shown below figure :-

     

    Now install the EntityFramework by writing Install-Package EntityFramework in package manager console.

     

    After this, it will install the latest version of entity framework as shown below in the figure.

     

     

    Now we have references of entity framework in our references as shown below in figure :-

     

    Now create a class which you want to be created as a table. I have created a class named Department and created two properties as shown below in code:-

    using System.ComponentModel.DataAnnotations;
    
    namespace CodeFirstSample
    {
        class Department
        {
            [Key]
            public int DepartmentId { get; set; }
            public string DepartmentName { get; set; }
        }
    }

    Where key is Primary Key and it will be auto incremented. While we insert record into the database.

    Now we will create a Database context class name it whatever you want i am using EntityContext as shown below in code :-

    using System.Data.Entity;
    
    namespace CodeFirstSample
    {
        class EntityContext : DbContext
        {
            public EntityContext() : base("name=conn") { }
    
            public DbSet<Department> Department { get; set; }
        }
    }

     

    Here DbContext is used to communicate with the database. And DbSet is used to make CRUD operations for that particular entity.

    Where "base("name=conn") { }", conn is the connection string name.

    Next task is to setup the connection string in App.config file as shown below :-

     <connectionStrings>
        <add name="conn" providerName="System.Data.SqlClient" connectionString="Server=ServerName; Database=DatabaseName;User ID=userid;Password=password" />
      </connectionStrings>

    Just write above tag below config sections in App.config file.

    Now we will use Program.cs file to write logic to create table and enter some sample data in database as shown below :-

    try
    {
        for (int i = 0; i < 5; i++)
        {
          var dept = new Department()
          {
             DepartmentName = "Dept" + i
          };
    	  
          using (var context = new EntityContext())
          {
    		//It will create the table if not exists otherwise it will enter record in database.
            context.Department.Add(dept);
            context.SaveChanges();
          }
        }
    }
    catch (Exception)
    {
      throw;
    }

    No if you run the project then it will create the object name dbo.Departments in the database in the mentioned config file.

    Next time if you again run the project then it will check if Entity exist or not if it is exist then it will insert the record the record in the table.

    Now if we want to change the entity or table from code behind using this approach. We need to re-create the entity by writing the following code :-

      //If any model class is changed and we want to update that, then we need to implment this class
       Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EntityContext>()); 

    It will recreate the table. If you have records in the table ,please dont't use it.

    Thanks for reading 

    Happy Coding!!

    Code First Approach in .Net

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: