Sunday, June 5, 2011

EF 4.1 Code First Approach

In this Blog post we are going to see Entity Framework 4.1 Code First approach.  Here I am going to create Small console application to demonstrate. First of all you may ask question what is code first?

EF code first means first Define the classes this is nothing but our MODEL , then EF will work with theses classes this is called CODE FIRST APPROACH. Here I am going to use  Nuget to get EF 4.1 Reference assemblies from the Internet.  Here is how you get it.

First Create C# Console application then go to tools menu in VS.NET 2010 

image

Once you click Package Manager Console you will provided to execute the  Windows PowerShell prompt to execute the command . The command we need to execute to get  EF 4.0 assemblies is

Install-Package EntityFramework.

image

Next create the Entity class and Context class as shown below

 

DB Context

public class ContactCtx :DbContext
  {
      public DbSet<Contact> Contacts
      {
          get;
          set;
      }
  }

 

Entity


public class Contact
   {
       public int Id
       {
           get;
           set;
       }
       public string Name
       {
           get;
           set;
       }
       public string Phone
       {
           get;
           set;
       }

       public string Email
       {
           get;
           set;
       }
   }

Here I am creating a contact that will be saved in DB.

class Program
  {
      static void Main(string[] args)
      {
          ContactCtx db = new ContactCtx();
         
          db.Contacts.Add(new Contact
          {
              Name = "Vasanth.v",
              Phone = "23232323",
              Email = "v@v.com"
          });
        int a=  db.SaveChanges();
        Console.WriteLine("DB ID is " +a);

       Contact c= db.Contacts.Find(1);
      }

    
  }

when you execute the program the DB is created and the records are added .  EF use SQL Express by default if do not specify .

image

Nandri(Thanks)

SreenivasaRagavan

No comments: