How to use EntityFramework CodeFirst to update your database

This tutorial will attempt to explain how to update an already existing database using EntityFramework's CodeFirst approach.
We need:
1.) VS2010 SP1
2.) NuGet
3.) EntityFramework 4.1
4.) EntityFramework.Migrations
  Steps: 1.) We need to make sure that we have Package Manager Console installed in VS2010 (Open the view).
  2.) In Package Manager Console execute:
    a.) Install-Package EntityFramework
    b.) Install-Package EntityFramework.Migrations

Delete all tables. Update-Database –TargetMigration:"0"
Update-Database Add-Migration InitializeWeddingDb

How to create a one-to-one relationship V1:
    [Table("WeddingProducts")]
    public class WeddingProduct : BaseEntity
    {
      public long WeddingMenuId { get; set; }
      public WeddingMenu WeddingMenu { get; set; }
    }

    [Table("WeddingMenus")]
    public class WeddingMenu : BaseEntity
    {
    }

   //On Context Class override OnModelCreating()
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
     modelBuilder.Conventions.Remove();
     modelBuilder.Entity().HasRequired(p => p.WeddingMenu).WithMany().HasForeignKey(p => p.WeddingMenuId);
     base.OnModelCreating(modelBuilder);
   }
V2 - This one has Cascade: Delete set to true by default
    [Table("WeddingProducts")]
    public class WeddingProduct : BaseEntity
    {
      public long WeddingMenuId { get; set; }
      [ForeignKey("WeddingMenuId")]
      public WeddingMenu WeddingMenu { get; set; }
    }

    [Table("WeddingMenus")]
    public class WeddingMenu : BaseEntity
    {
    }

   //On Context Class override OnModelCreating()
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
     modelBuilder.Conventions.Remove();
     //modelBuilder.Entity().HasRequired(p => p.WeddingMenu).WithMany().HasForeignKey(p => p.WeddingMenuId);
     base.OnModelCreating(modelBuilder);
   }
How to call stored procedure in codefirst (can be achive using the DbContext class):
IList weddingMenuList = _context.Database.SqlQuery("spGetWeddingMenu").ToList();


To call with parameter
SqlParameter param = new SqlParameter("@productId", productId);
IList weddingMenuList = _context.Database.SqlQuery("spGetWeddingMenu @productId", param).FirstOrDefault();
Note that model-first and code-first should not be use on a single project. Since model-first, is the first to come out in the market I assume most of us use this first then want to try code-first. You can create a class library for this. So they are on different assemblies.

Reference: http://blogs.msdn.com/b/adonet/archive/2011/09/21/code-first-migrations-alpha-3-released.aspx
How to use EntityFramework CodeFirst to update your database How to use EntityFramework CodeFirst to update your database Reviewed by Edward Legaspi on Thursday, November 03, 2011 Rating: 5

No comments:

Powered by Blogger.