Saturday, 1 November 2014

Entity Framework Code First (Data Migrations) PART-1


In this blog post we are going to learn about entity code first migrations. Using EF code first approach you have complete control over classes are written. But as soon as application grows and there are some new features need to be added and your classes may change. Entity Framework Code Migrations allows you to handle these migrations.
















Constructor in context:

Without parameter: If no parameter passed then it creates database in local SQL express with name that matches {namespace}.{context class name}

Like with our previous code sample:
EFCodeFirstExample.DataContext

namespace EFCodeFirstExample
{
 public class DataContext : DbContext
    {
        public DataContext() : base()
        {
        }
    }
}

With Name specified: If name specified then database will be created with the given name.

public class DataContext : DbContext
    {
        public DataContext() : base("SampleDB")
        {
        }
    }

With Connection string name specified: connection string name specified in web.config/app.config file.

public class DataContext : DbContext
    {
        public DataContext() : base("ExampleConnectionString")
        {
        }
    }

Database will be created with name specified inside connection string. ("Example-ByConnectionString")

<connectionStrings>
  <add name="ExampleConnectionString"
  connectionString="Data Source=.;Initial Catalog=Example-ByConnectionString;Integrated Security=true"
  providerName="System.Data.SqlClient"/>
</connectionStrings>


No comments:

Post a Comment