Entity Framework Code First Simplicity

Ok, so you've heard all about Entity Framework (EF), and about how marvelous it is, so you've gotten all fired up about it, and thought woo, yea! Time for me to get my EF hat on. Then you start reading the docs, and looking at the examples, and suddenly the realization sinks in. None of this is as simple as the video you watched would have you believe, you scratch your head in disbelief. All you want is to have your application talking easily to your database by the end of the week, but now it seems like it's going to take you that week just to figure the rest out.

It's Like any Other Technology in IT

We've all been there, and while it might look like it's going to take you a million years to tame this, Entity framework is just like any other technology in IT.

If you've spent any time at all in the industry, then you'll know that there's a dozen different ways to do each thing. The trick is to not sit and try to cram it all in, in one go, but rather consume it in little bite sized chunks. That's exactly what I found when I first started using Entity Framework.

In this post I'm going to show you the absolute simplest way of getting started using Code First.

Why Code First, and not Database First or Model First?

As a developer on the Microsoft platform, the last thing you want to be doing is putting another hat on. We already have enough hats to wear without needing to be a DBA too.

To me, Code First is the perfect balance; it keeps me focused on my code, and I only ever have to deal with objects. Once everything is running I don't really have to think about things like tables, because everything just works and works well.

Others may disagree however, and there's been plenty or religious wars over the years on this and other subjects, one which I'm not going to get involved in.

First Things First, Create a Database.

If you don't already have a database, then you'll need to pop open SQL Management Studio and create one.

If you don't control your database server, then you'll need to ask your network admin/DBA/IT support person to create one for you. However you do it, for reliability sake unless corporate policy dictates otherwise, ask for an SQL login and make sure that the login name has full read/write privileges on the new database.

If you have control of the database, then from SQL Management Studio, right click on databases in your server tree browser and select new database.

I'm not going to go through the entire process here, but what I generally do then is to make a new login, set the default database for that login as the database I just created, then go back to the new database properties and set the owner as the login I just created.

That's all you have to do outside of Visual studio.

From Now on its Code All the Way.

Create yourself a new project in Visual Studio. For the purposes of this post I'm using VS2013 Ultimate, and I've created a simple winforms app with a button on so that I can test it.

For you, well you create any project type you’re comfortable with. I would strongly recommend that you don't use any project templates that have any pre installed dependencies or code in them though as you never know what might, and might not get in your way while doing this.

Once you have your project up and running, right click on your project’s references entry in your solution explorer, then select 'Manage NuGet Packages'

Manage NuGet Packages

When your NuGet package manger opens, type 'Entity' (that's all you need...) into the search box in the online tab and wait a few seconds.

NuGet Package Manager

Click the install button, then close the NuGet dialog.

EF is now installed with its basic settings. Everything you need to connect to a standard Microsoft SQL Server instance is present and ready to use.

From this point on, how you organize your code should always be in the best interests of your project. For me I always keep my code in a folder called 'Classes' and any objects that are related to my database in a folder called 'Entities'. If you wish to do things differently, just remember to adjust namespaces as required.

Right click on the home node (top of the tree) of your project and 'Add -> new folder'

Create two folders, one called 'Classes' the other called 'Entities'; your solution explorer should look something like the following:

Solution Explorer

Right click on your 'Classes' folder, and 'Add -> Class', call this class 'DataAccess' and click 'Add' to add it to your project. The class file template should then open in Visual Studio, looking something like the following:

namespace MSSQL_EFCF.Classes
{
classDataAccess
{
}
}

We’re going to modify this class to be our Entity Framework 'Database Context'. Make sure your class is public, then extend the class so that it inherits from 'DbContext' as follows:

Also remember to make sure you add 'System.Data.Entity' to your classes using clause (I'm omitting using clauses in my code samples for brevity.

Once you have the framework for your code, you then need to create an empty constructor and make a call to the base class setting the name of the connection string you wish to use.

Lastly, you'll need to add one or more 'DbSet' entries to your class to represent the tables in your database; we're only going to use one this time, but in a future post I'll introduce 'Entity Framework Migrations,' which will allow your data model to evolve over time and change as your application grows.

You'll also most likely get a compile error at the moment, because we've not yet created any entities to represent our table objects. Don't worry if you do, all will be put right soon.

If you've followed me, then your class should now look a little bit like the following:

And that's actually enough to get EF to create a table in your database (once you have the object itself created.

'MyConnectionString' is created the same as any other connection string, by editing your app.config or web.config files; just remember that the name you specify here is the name you'll need to give your connection string entry.

At this point, for the most part, Entity Framework will rely on a conventions based approach to work out specifics of your database. Most importantly if it needs to have restrictions such as field lengths and key settings, or you need for some reason to override the conventions, then you will need to create an override in your data class to override the 'OnModelCreating' method used by EF at start-up. Within this override you use a 'ModelBuilder' to configure certain aspects of your model to work the way you want them to.

In our class, we’re simply just going to set the key column and table name, using the following:

Remember that you also need to set your connection string correctly too. In my case as described previously, I created a new database (which I called 'netnutsandbolts') and I created a user to own the database and act as a login for it.

In your XXXX.config file, under the connection strings section, you need a key with the same name as the connection string you used in your data context, something like the following:

One thing to be aware of with connection strings. Depending on your version and configuration of Visual Studio, you may have database technologies like "Local DB" available, or "MSSQL Compact". If you don't get your connection string correct, or fail to include it, Entity Framework will attempt to see if it can use one of these. What can happen here is that your app appears to work, but you then spend hours scratching your head, wondering why the database you were supposed to be writing to still has no data in it.

If you have any ideas for this column, or can think of anything you'd like me to cover, don't hesitate to reach out to me. I can generally be found hovering around on Twitter as @shawty_ds , or you can find me in the 'Lidnug' users group on Linked-in that I help to run.

Comments

Nice read, easy to understand.

GDB

Posted by Gavin
on 08/29/2014 01:30am

Great post. I've used it as a good refresher to kick-start a short project using I'm on with now.
As a front-end backgrounded bloke I probably need as much help as possible with the back end pieces.
As a possible addition to this, perhaps we could talk about using linq when retrieving data from the db with EF? What is the more efficient use etc and the finer details of bringing out the best in EF perhaps?

RE: GDB

Posted by Peter Shaw
on 09/26/2014 07:39am

Hi Gavin,
thanks for the kind words, and I'm glad you found it helpful.
If you click on my name at the top of this post, you should be able to link to all my other articles. I do have a Linq to Objects one already which may be of some use.
That said, I'm planning on doing a future article that extends on this one to help you build a full data layer directly in code, I can't however say when that will be.
Do however feel free to ping me on twitter as @shawty_ds if I have time and am not busy I don't mind answering the odd small question here and there.

Top White Papers and Webcasts

Come take a deep dive into the XtremIO architecture to learn how our powerful and unique meta data driven system has redefined the Copy Data Management (CDM) landscape. Hear how other organizations have dramatically sped up their test and development processes and added self service capabilities while maintaining governance & control. The magic is in the meta.

The road to a successful master data management (MDM) program can be full of detours and dead ends. In this white paper, Dan Power and Julie Hunt from Hub Designs identify the eight worst practices when planning and designing a MDM and data governance program, and show you to get it right. (Updated for 2016)