Entity Framework Code First Example

Reading Time: 3 minutes

In this tutorial, Entity Framework code first example is given. We will continue from previous post and heaving code already we will make the database. This is actually the point of Entity Framework code first concept: to have classes in the C# code and by using them and Entity Framework to create real database on the server. Let’s remind of the context class that we already have.

class DepartmentContext : DbContext

public DbSet<Department> Departments { get; set;}

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


Let’s expand this code in order to create new database. End let’s make empty data base first.

We need now to connect to this empty database in our application. Let’s go for it.

Add new connection.

Change connection to Microsoft SQL Server.

Then choose server and the empty database.

After successfully tested connection, we should be able to see connection in server explorer.

Now we need to add DataSet to our project in order to obtain connection string. So, go project, then add, New Item.

Then choose Data, DataSet.

Then just drag connection to Dataset sheet.

Now connection string is ready in App.config

It should look like in figure bellow.

Copy connection stringĀ  from there including double quotes, and copy it in db context with at symbol in front added.

Tagged with:

Leave a Reply

Your email address will not be published. Required fields are marked *