/ Entity Framework

All you need to know about entity framework code first migrations

By introducing LINQ (Language Integrated Query), Microsoft brought around a revolutionary change in how we (.net programmers) process data, let the data be in memory structures like arrays, list, collection or a database far far away. Beautiful thing is that the LINQ statements remain exactly (well, almost) same if you switch the source object. For eg. (And I'll be using extension methods and also introduce very basic code-first model)

    //These are our classes to hold view related information
    public class CustomerViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class CustomerGroupViewMode
    {
        public string City { get; set; }
        public List<CustomerViewModel> customers { get; set; }
    }

And somewhere in your business layer you have written this piece of code, as at the time of writing this code, Data Access Layer was not ready so you had to come-up with some dummy models to complete the code and may be pass unit tests.

    //Dummy customer class 
    public class DummyCustomer
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string State { get; set; }
    }

and finally your business logic. (initWithDummyInformation takes in a list and populates it with dummy values so as to have something to process. In actual scenario we will never go about this way, we'll be using a more sophisticated ways, like IoC)

    var customers = initWithDummyInformation(new List<DummyCustomer>());
 
     customers.Where(c => c.State == "Gujarat")
              .GroupBy(c => c.City, 
                      (k, c) => 
                        new CustomerGroupViewMode() {
                                 City = k, 
                                 customers = c.Select(cust => 
                                     new CustomerViewModel() { 
                                         Id = (int) cust.Id, 
                                         Name = cust.Name }).ToList() 
                              }
                    )
                    .ToList();

For those who are not familiar with LINQ or extensions usage, This weird looking query does a very simple job, it groups all the customers by city with in Gujarat state and then fills up the view model. and when the DAL is ready, suppose this is your small DAL fragment.

    public class Customer
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
    }

    public class CustomerContext : DbContext
    {
        public DbSet<Customer> Customers { get; set; }
    }

These (approximately 13) lines of code does the job, when you try and access Customers property of CustomerContext, Entity Framework will create a database (if its not there), will also create tables (if they are not there) and when you execute LINQ over it, EF will translate LINQ statements to SQL, send it over to the databse server, receive the response back and finally materialize the objects. Woh! That was a lot of work man! - thanks EF ;), now to wire-up your code in business layer with DAL, replace

    var customers = initWithDummyInformation(new List<DummyCustomer>());

with

    var context = new CustomerContext();
    var customers = context.Customers;

and wallah! When I did similar stuff a few years back, I was mesmerized with the power of LINQ.

Well, you must be thinking that why this guy is going on and on about LINQ even when the title says its about migrations, we are about to enter migration scenario. Say, now your technical lead says that for performance reasons, you should index State, and you are like, but my database is already created and populated, how am I suppose to change my DB schema now, just to apply indexing to State column, I'll have to go through a lot of overhead, Isn't there an easy way to get this done? Well my friend, the answer to your question is Entity Framework Migrations.

Entity Framework Migrations is a long and I must say very important topic if you are going to move forward with code first approach in your DAL, I suggest you pay extra attention. I have decided to break this (somewhat huge) topic into a few smaller sub sections and will cover each of them in a separate blog.

First of all we'll go about the most straight forward and simple way, that is Automatic migration. Once this is done, we'll be having the basic understanding of what migration is and how it works and then we can dive into a bit more deep wit manual migration using package manager, it will also cover Up and Down transition that EF internally uses while Creating or Droping DB objects. Now we can dive in a bit more deeper and see how to automatically migrate a Db context which has only parameterized constructor(s).
Once we are done with all of above mentioned topics, I am very sure that you'll be able to handle almost every migration scenario with Entity Framework Code First.

Cheers and Happy codding fellows!

Dave Amit

Dave Amit

Howdy folks! I am Dave Amit, an accidental programmer, father to a lab puppy, hubby to a beautiful wife, addicted to puzzles & a noob blogger. This is my effort to simplify odd codes from the wild.

Read More