Entity Framework 6 – Migrations

Migrations are needed in our day to day work and EF migrations story has become a lot better over the last year. When your database changes rapidly then migrations are needed to keep pace. Ofcourse this is nothing new, but it wasn’t available in EF before.

Enable Migrations

To enable the migrations go to Tools -> Library Package Manager -> Package Manager Console.
Type Enable-Migrations in the console.
-Force parameter is optionally available if you want to overwrite an existing migrations.

Creating a migration

Once the migrations are enabled, use the Add-Migrations command to add a migration.
Give a logical name to the migration, attach a issue number if needed to the migration name like myawesomemigration-issue#1234. It really helps when you want to go up and down the migrations.
When you choose to enable migrations, do it in the correct project if you have multiple projects in the solution.
Once the migration has been added, then you will see two new files within a new folder Migrations pop in. One of these is the migrations file which will have your nice name and the other one is Configuration.cs which will have your configuration.
Your awesome migrations file will have all your create table syntax, this seems to be a DSL. You can do your funny bits here, add an Index tweak mania can begin here. Do read the file carefully though for the first few times. It should not be too dense and it should all make sense. If something looks off highly likely that your configuration in the model is fishy. It has two methods which allow you to move up and down between the migrations.

Configuration.cs is a useful class. It has the seed method with which you can seed you database. You can seed your db with test data which you will need for running the system tests (which you should with EF).

Updating your database

All said and done, time to update our database to the latest version. In the package manager console, write
Update-Database -Verbose. The verbose flag gives you back the sql as well for you to see. Options are available to script it out to a file as well if you want to hand it over to someone else.

As of this writing EF 6 beta has broken this bit bug
You should be safe on previous bits ( till alpha or EF 5 and below ).

Have a look at your database when the command finishes, your database should be updated.

Irritant

Next, I will write about a gotcha that made me think long and hard if I was very dumb.

Entity Framework 6 – What’s new ?

EF6 is still in alpha stages but you can go grab it now via nuget.
What is new ?
A whole lot find about it here EF6

Also, do read this post about migrating to EF6 if you are migrating an existing application.
EF6 Migration

I was able to use a few of the features that are new. I had earlier blogged about EF(EF 4.1) when V4.1 came out, I am basically using the same model to see if life is any easier with V6. The model is fairly simple. There are users, users can questions and questions are of different types. A user creates Test which is composed of many questions.

Earlier, there was no easy way of doing Enum in EF Code First. That limitation is no longer there.
Now, the questions can be of varying difficulty levels so now we can do the following.

    public enum Difficulty
    {
        Trivial = 1,
        Easy = 2,
        Medium = 3,
        Hard = 4,
        Difficult = 5
    }

    /// <summary>
    /// Question is the base type which describes a Question. Other types derive from Question.
    /// </summary>
    public class Question
    {
        /// <summary>
        /// Gets or sets the Difficulty
        /// </summary>
        public Difficulty Difficulty { get; set; }

....more properties 
    }

Similarly we can have UserRole as well.

EF now has the option to specify the default schema is also available now. It can be done as shown below.


modelBuilder.HasDefaultSchema("ParikshaDev");

EF now has the ability to provide custom conventions as well. The following conventions are available to us.

  • Lightweight Conventions
  • Configuration Conventions
  • Custom Attributes
  • Model-based Conventions

Read more about it here EF Conventions.
I will cross-post an important point about the order of execution. If you have many conventions then the order will become important. I haven’t written a lot of conventions but my guess is that this could get tricky if not done with care.

  1. IConfigurationConvention-based and lightweight conventions
  2. IEdmConvention-based conventions
  3. IDbConvention-based conventions
  4. IDbMappingConvention-based conventions

A conventions that I have used is Lightweight conventions. We sometimes want to append custom names to our table names as per the convention of our customers.


modelBuilder.Entities().Configure(_ => _.ToTable("CustomTable"+ _.ClrType.Name));

Similarly, other conventions are also available. The most common ones that I see being used will be Lightweight and Configuration Conventions.

Next, we will have a look at enabling migrations and an irritant that made me go nuts for a few months.

Console 2 – Command Line awesomeness

1. What is this ?
Ever felt that the command prompt fall a little short of your expectations ? You want it to feel like the power toll and not just a tool.

2. Where do I get it ?
You can download it from here Console2

3. Help me set it up .
Refer to Scott Hansleman’s blog post Original Post.

Now, if you have successfully managed to get Console2 working note carefully what the last part in Scott’s post said
Console2 is a great little front-end for your existing shell, no matter what it is. Note that Console2 isn’t a shell itself, it’s just a face on whatever you are already using.

4. Let’s make the world a better place by adding Git Bash to the the tabs.


Title : GitBash
Icon : C:\Program Files (x86)\Git\etc\git.ico
Shell : C:\Program Files (x86)\Git\bin\sh.exe --login -i
Startup dir : c:\Users\Ashutosh ( or whatever your path is )

Console2

Console2

All looks nice, the world is a better place.

Entity Framework – Generic Repository Pattern – Part 2

In the previous post I wrote about an implementation of the Generic Repository pattern for EF. There is so much data on the web that it is difficult to understand what might actually work for you. All of this can drive you Crazy. Throw in my version of crazy as well Crazy2

Now that you have checked out the links and gone crazy reading how we all wanted a code review for this, it tells you the developer about the levels of confusion this pattern can create. One of my first thoughts was something like this Honestly, I don’t even remember what my exact thoughts were when I was prototyping the code.

In Part1 I did say that I will highlight some of the issues that I faced (remember YMMV). I didn’t do TDD for this ( sue me :) ).

  • Testing is not as pain-free as it seems. What layers to test and how to test them ?
    After all of this code is for separating components and making life easier in the long run by increasing our confidence in the code.
    If EF is already a UoW and Repository then what are doing building a layer on top of this ?
  • We end up having a service layer anyway since our application logic is often non trivial and needs to be kept separate. Then the real fun begins with tests.
  • Mocking EF is a pain since you don’t have an IDbContext available. Get your fake data in there , then mock the repository and then mock the repository methods, then if you want to mock something like Includes() you will have some real fun. The idea is not mock EF, but even checking anything that sits on top of it can become an exercise in itself.
    After writing the tests, I can confidently say that my confidence in my code had not increased the manner I had expected (you bet this confidence thing is funny business) . I often had the feeling of buyer’s remorse.
  • It felt like I was on the wrong path. What do we really care about ? We need to get our data in and out of our database. That is it. How does making an abstraction help? It does not help that much. We are working exactly with the IQueryable that EF gives us back. Some implementations also have methods like FindById(..) , SortBy(..) etc…
    We need to concentrate on queries in our application. Make queries first class in your application.
  • Was all of this useless ? No, not quite. Implementing the Repository Pattern this way is, the pattern is not useless.
    We leak our data access technology Entity Framework into the Application Layer. A UnitOfWork driven implementation is actually very useful.
    I have not given that a go in code but here is something to start with Repository Pattern

In conclusion, it was both fun and enriching to hit roadblocks and see why the developers are moving to and from the Repository Pattern. I was working with EF6 and that came with its fair share of headaches. I will blog about that soon. Stay hungry, stay awesome.

Team City – Recover Admin Password

The trials and tribulations of this world are beyond me. Sometimes, a simple gesture can save your life.
I lost(forgot, forgive my small brain it has to keep up with a day job) my TeamCity login details.
Searching online will lead you to this place Forgot Team City Password.

The solution there is mighty correct barring two things. One, your TeamCity data directory path is likely to C:\ProgramData\JetBrains\TeamCity\ on a windows box and not C:\users\foo\TeamCity.
So,


Step 1 Stop TeamCity service ( either through services.msc or the bat files ).

Step 2  Open CMD as <strong>ADMINISTRATOR</strong> 
(don't forget the admin part you will go bonkers trying to figure out what is happening)
and go to C:\TeamCity\webapps\ROOT\WEB-INF\lib

Step 3 type -cp server.jar; hsqldb.jar ChangePassword USERNAME PASSWORD C:\ProgramData\JetBrain\TeamCity

If all is successful then you password has been reset and you can login. Here’s hoping to a few hours saved for anyone who comes around to reading this.

My Development Setup

OK so Visual Studio 2012 has been been here for some time. Below is my current set up of VS 2012.

Extensions:

1) Git Source Control Provider for Visual Studio
Git is my personal source control of choice. I don’t have the luxury of using it at work and it just reminds me of what I miss at work. You can get it from here. Git Source Control Provider

2) Gister
You got love this one. Helps you make Gists straight from VS and even copies the Url to the clipboard. It is here Gister

3) NUnit Test Adapter
Nothing much to say about this. I do see a lot of people starting to look at xUnit. Keep an eye out for that one.

4) Workspace Reloader
Does exactly what the name says. Your workspace is as it is after you make source control updates.
Workspace Reloader

For now this is my limited tooling to support my day to day work. Only you put in so much as you need.

Outside of VS I have the following

  • Windows 8
  • SublimeText2 ( this is so neat I plan to have a dedicated post for this )
  • Github for windows
  • Sql server Express
  • Oracle Virtual Box
  • GitExtensions
  • TeamCity
  • LightTable ( just for fun )
  • Eclipse for Scala Devlopment
  • Usual army of browsers ( chrome, IE10, Firefox, Chrome Canary,etc..)
  • Code Writer for windows 8
  • Notesphere for windows 8 ( this is an underrated note taking application )
  • Tasks Application for Windows 8 by Telerik ( this one is a gem )
  • Dropbox
  • Skype
  • Skydrive
  • MarkDownPad

NUnit Test Code Snippet for Visual Studio 2012

What are we doing ?
We are trying to create a snippet for creating an NUnit test.

How do we do this ?
We go write a snippet.

The snippet is here NUnit Snippet

Save it under ..\Documents\Visual Studio 2012\Code Snippets\Visual C#\My Code Snippets

Now go add the snippet.
Go to Tools in VS -> Code Snippets Manager -> and Import after clicking on the Snippet.
That’s it, we are done.