Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Entity Framework Code First: Let's Try It

4.77/5 (31 votes)
27 Jan 2012CPOL3 min read 166.6K  
EF Code First: First try

Introduction

You heard about Entity Framework and want to try it. Here, you can find a very simple example of how to create a first class and a first table from this class using Code First.

Using the Code

We will create a Console Application, add a class Person and generate the database from this class. Open Visual Studio and create a Console Application. I called mine EFFirstSample. Now, you have to allow code first on your project. To do that, add Entity Framework from NuGet package. Open Visual Studio, go to Tools -> Library Package Manager -> Manage NuGet Packages and select EntityFramework package. It will add all references to your project.

Add package

Once added, check references in your project. EntityFramework should have appeared. You should also see a new file package.config. This file contains all information about NuGet packages installed. Ok, so now, we can start our project. We will first add a new class file, Person.cs and declare four properties: an ID, a lastname, a firstname and a date of birth, like this:

C#
public class Person
{
    public int PersonId { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public DateTime BirthDate { get; set; }
}

Now, we will create a class to manage the link with the database: our DBContext. Add a new class MyContext.cs and let it inherit from DbContext class (add System.Data.Entity as using):

C#
using System.Data.Entity;

namespace EFFirstSample
{
    public class MyContext : DbContext
    {
        public MyContext()
        {}
    }
}

So now, we will tell the context what should be created in the database. Add the following line:

C#
public DbSet<Person> Persons { get; set; }

It allows the context to know that it will contains a collection of Persons (and that a table Person should be created). If we run the application, nothing will happen. You can check, connecting to your SqlExpress instance. Let's add some code in our Console, to call our context. Go to Program class and modify it like that:

C#
static void Main(string[] args)
{
    var person = new Person {FirstName = "Nadege", 
    LastName = "Deroussen", BirthDate = DateTime.Now};
    using (var context = new MyContext())
    {
        context.Persons.Add(person);
        context.SaveChanges();
    }
    Console.Write("Person saved !");
    Console.ReadLine();
}

We just create a new Person and add it to the database. Now, run the application and check the message before closing.

First launch of the application

It's time to check in the person was well created. Connect to SqlExpress and check that a new database was created:

On the Toolbar Server Explorer, you should be a Data Connections node. If the toolbar is not visible, go to View -> Server Explorer

Data Connection node in Server Explorer toolbar

Right click on the node and select Add connection. A new window appears. Add your server (.\SqlExpress if you use SQL Express) and select your database in the dropdownlist. Here is what I have :

Add Data Connection

Test your connection and validate with the OK button. You should now see your database.

Screen capture of server explorer showing a table People

You can see a People table and an EdmMetadata table. The first one represents the table corresponding to your Person class. Why is it named People? Because of naming convention. EF Code First uses pluralization rules and so our DbSet Persons is rename People, singularized. Right click on the table name and select Open table definition. You should see something like that:

Image 6

You can see the PersonId has been created as a primary key. How is it possible? We don't specify anything! It's simple. Code First uses naming convention to determine which property should be used as primary key. If you name a property TableNameId, Code First will see that this property will be used to define the primary key. Very simple. There is another way to define the property that would match the primary key. We will see that in a future post. The other table, EdmMetadata, stores a hash that will allow EF to check if there is modification to the model or not.

You just create your first, simple, application with Entity Framework Code First. In a future post, we will see how to add multiple tables with foreign key.

History

  • January, 2012: First post
  • January, 2012: Added explanation on how to connect to the database

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)