Click here to Skip to main content
Click here to Skip to main content

Entity Framework Code First: Let's Try It

, 27 Jan 2012
Rate this:
Please Sign up or sign in to vote.
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:

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):

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:

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:

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:

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)

About the Author

Nadege Rouelle
Architect
France France
I'm coding in .Net since 9 years, most with ASP.Net and SharePoint and a little using WPF, MVC, Windows Phone 8 and WinRT technology.
I have learned so much reading others experience and tutorials, or tips so I try to do the same, keeping learning from others of course.
You can also find my blog here : http://sharemstips.wordpress.com/
Follow on   Twitter

Comments and Discussions

 
QuestionError Pinmemberdtmr.tomar2224-Apr-13 3:40 
GeneralMy vote of 3 PinmemberSami Ciit10-Jan-13 6:46 
GeneralMessage Automatically Removed PinmemberMember 468187416-Aug-12 23:53 
GeneralMy vote of 5 PinmemberBalaThakur2-Aug-12 21:24 
GeneralMy vote of 4 PinmemberGaurang Naik1-Jul-12 23:57 
QuestionThank you very good Pinmemberregb23-Mar-12 11:37 
AnswerRe: Thank you very good PinmemberNadege Deroussen3-Apr-12 8:04 
QuestionConnecting to the database Pinmemberdarrellp25-Jan-12 9:28 
AnswerRe: Connecting to the database PinmemberNadege Deroussen25-Jan-12 20:49 
AnswerRe: Connecting to the database PinmemberNadege Deroussen29-Jan-12 22:32 
SuggestionThis article is a good addition and has some features to original article on MSDN Pinmemberagorby21-Jan-12 9:33 
GeneralRe: This article is a good addition and has some features to original article on MSDN PinmemberNadege Deroussen25-Jan-12 20:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 27 Jan 2012
Article Copyright 2012 by Nadege Rouelle
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid