Code First Approach in ASP.NET

kgovindarao523-21772
Posted by in ASP.NET category on for Beginner level | Points: 250 | Views : 3930 red flag
Rating: 4.25 out of 5  
 8 vote(s)

Code First Approach, the name itself suggests that “coding the required classes (Entities) First, and then generating the Database required to persist the data”.

Introduction


  • Code First Approach, the name itself suggests that “coding the required classes (Entities) First, and then generating the Database required to persist the data”.

  • Code first Approach avoids us to work with visual model designer (EDMX) completely.

  •  There are two types introduced for Code First approach,
    • DbContext and
    •  DbSet. 
  • DbContext is a simplified alternative to ObjectContext(which is specific to your conceptual model, including predefined connections) and is the primary object for interacting with a database using a specific model. 

  • DbSet is a simplified alternative to ObjectSet and is used to perform CRUD operations against a specific type from the model in Code First approach. 

WORKING WITH  CODE FIRST APPROACH


1. Take a New Project In Visual Studio 2010.

2. Take a class file and Name it as Model.cs


3. Install EntityFramework using NuGet Package manager

Now if we want to work with code first approach we need to install EntityFramework in our solution, To do so, go to: Project Menu --> Open Manage NuGet  
--> select Online tab at left side --> In Search Online text box, Type EntityFrameWork --> Click on Install Now Build the Solution using Ctrl+Shift+B or F6



4. Define Classes (Entities) as per your requirement
Go to Model.cs Class add in using System.Data.Entity; in usings Section.

[Table("PersonalProfile")]
    public class PersonalProfile
    {
        [Key]
        public int Person_ID { get; set; }

        [MaxLength(40]
        public string First_Name { get; set; }

        [MaxLength(40]
        public string Middle_Name { get; set; }

        [MaxLength(40]
        public string Last_Name { get; set; }


        [MaxLength(10)]
        public string Gender { get; set; }

        [DataType(DataType.Date)]
        public DateTime? DateOfBirth { get; set; }

        [MaxLength(40]
        public string MotherTongue { get; set; }

        [MaxLength(150]
        public string FatherName { get; set; }

        [MaxLength(150]
        public string MotherName { get; set; }


        [MaxLength(150]
        public string Personal_Email_ID { get; set; }

        [MaxLength(20]
        public string Personal_PhoneNo { get; set; }

    }
Few points we note while creating an entity class
*. The entity must contain a primary key (by Specifying KEY() on top of the property)
*. By Default class name itself a table name in database, if you want another name you can Name it using TABLE() 
*. The remaining annotations like MAXLENGTH(), DATATYPE(), are providing limitations on Columns.

5. Creating Context Class

Now, our classes (rendered as tables) are ready. We have to create a database.  Right?
To create a database first we need to create context class importing DbContext class.

For ex:
public class ProfileContext : DbContext 
{
public ProfileContext()
            : base("ProfileContext")
        {
            Database.SetInitializer<ProfileContext>(null);
        }


public DbSet<PersonalProfile> PersonalProfiles { get; set; }

}
It allows us to specify DbSet for the entities we created. 
The “Context” class (here, ProfileContext ) name will be rendered as database name and the DbSet s will be the tables in the database.

6. Define Connection String in Web.Config
 Now, Open web.config file in solution explorer and in configuration section add connection string as follows


The points to be noted that, The connection string name must be same as your context name (i.e. ProfileContext) , If you want your custom named connection string you have specify it in :base(…) as defined in above class.

7. Enable code first approach in your solution and create database

The next and important step is enable code first approach in your solution.

Steps to be followed:
  • Go to Package Manager Console in Tools tab as shown in fig.



  • Now initially we need to enable migrations
    by typing  the command “enable-migrations”  in Package Manager Console and press enter key.



  • After enabling migrations we need to add migration initial
    by typing command “add-migration Initial” and press enter key. 
    In Solution Explorer, This will create “Migrations” Folder with  “initial.cs” and  “Configuration.cs” and database with the specified Context name.

  • Now in “Configuration.cs” we can perform CRUD operations in “seed” method as shown in figure.



    As the Red circle in above fig you can write an initial data by specifying properties like:
    context.PersonalProfiles.AddOrUpdate(new PersonalProfile() { Gender = Gender.Male }, new PersonalProfile() { Gender = Gender.Female });

  • Now finally,  to update data into DataBase,
    we need to execute command “update-database” as shown in fig.

8. View your  Data in your database 
To view the data in database, click on “show all files” icon in solution explorer and in App_data double click on created ” .sdf ” file. We can now view table data by right clicking on the table and clicking on “show table Data”.


Conclusion


In this article, we learned how to develop a project with Code first approach in ASP.NET.

Page copy protected against web site content infringement by Copyscape

About the Author

kgovindarao523-21772
Full Name: Govinda Rao
Member Level: Bronze
Member Status: Member,MVP
Member Since: 4/17/2013 7:40:40 AM
Country: India
Thank you, Govind
http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)