Click here to Skip to main content
15,391,859 members
Articles / Programming Languages / C#
Posted 21 Jan 2012

Tagged as


50 bookmarked

Entity Framework Code First: Let's Try It

Rate me:
Please Sign up or sign in to vote.
4.77/5 (31 votes)
27 Jan 2012CPOL3 min read
EF Code First: First try


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())
    Console.Write("Person saved !");

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.


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


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


About the Author

Nadege Rouelle
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 :

Comments and Discussions

QuestionDownload source code Pin
isaacarsenal7-Nov-17 5:53
Memberisaacarsenal7-Nov-17 5:53 
QuestionDon't add data to DB Pin
karench28-May-17 0:58
Memberkarench28-May-17 0:58 
QuestionOther easy way to create code first database Pin
Member 117482382-Apr-16 5:40
MemberMember 117482382-Apr-16 5:40 
GeneralRe: Other easy way to create code first database Pin
PIEBALDconsult2-Apr-16 6:00
professionalPIEBALDconsult2-Apr-16 6:00 
GeneralMy vote of 5 Pin
VasanthBuild2-Nov-15 21:43
MemberVasanthBuild2-Nov-15 21:43 
Questionwhere do you add this code 'public DbSet<Person> Persons { get; set; }' Pin
varun15028-May-15 3:26
Membervarun15028-May-15 3:26 
QuestionError Pin
dtmr.tomar2224-Apr-13 3:40
Memberdtmr.tomar2224-Apr-13 3:40 

Dear sir,

there is no method find like add()instead there is a addobject() option coming .

why the add method not comming.
GeneralMy vote of 3 Pin
Sami Ciit10-Jan-13 6:46
MemberSami Ciit10-Jan-13 6:46 
GeneralMy vote of 5 Pin
BalaThakur2-Aug-12 21:24
MemberBalaThakur2-Aug-12 21:24 
GeneralMy vote of 4 Pin
Gaurang Naik1-Jul-12 23:57
MemberGaurang Naik1-Jul-12 23:57 
QuestionThank you very good Pin
regb23-Mar-12 11:37
Memberregb23-Mar-12 11:37 
AnswerRe: Thank you very good Pin
Nadege Rouelle3-Apr-12 8:04
MemberNadege Rouelle3-Apr-12 8:04 
QuestionConnecting to the database Pin
darrellp25-Jan-12 9:28
Memberdarrellp25-Jan-12 9:28 
AnswerRe: Connecting to the database Pin
Nadege Rouelle25-Jan-12 20:49
MemberNadege Rouelle25-Jan-12 20:49 
AnswerRe: Connecting to the database Pin
Nadege Rouelle29-Jan-12 22:32
MemberNadege Rouelle29-Jan-12 22:32 
SuggestionThis article is a good addition and has some features to original article on MSDN Pin
agorby21-Jan-12 9:33
Memberagorby21-Jan-12 9:33 
GeneralRe: This article is a good addition and has some features to original article on MSDN Pin
Nadege Rouelle25-Jan-12 20:47
MemberNadege Rouelle25-Jan-12 20:47 

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

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