Chlodny series Day 3: Connect Web Api to Entity Framework

Now that the existing database has been reversed engineered and the domain classes are set, it is time to wire up those domain classes to the main project.

Add the DataAccess project to the ChlodnyWebApi project.

  • Right click ChlodnyWebApi
  • Select Add reference
  • Select project
  • Select DataAccess
  • Click Add and then close

In the DataAccess project the reverse engineering tool created an app.config file.  This file can be deleted.  In the web.config file a connection string needs to be configured.  It should look similar to the following:

<add name=”ChinookContext”
connectionString=”Data Source=.\sqlexpress;

Initial Catalog=Chinook;

Integrated Security=True;Pooling=False” />

For now we will initialize the connection in Global.asax in a later article I will show how we can move this to Web.config.

Open up the Global.asax file and add a reference to the following

  • using System.Data.Entity;
  • using DataAccess;

Then locate the method Application_Start and set the initializer.  Until migration is setup

Database.SetInitializer(new CreateDatabaseIfNotExists<ChinookContext());

For now the initializer is set to only create if the database does not exist.

Now that Web.config is handling the initializer go to the ChinookContext and delete the constructor that sets the initializer.

The final thing left is to add Entity Framework to the DataAccess project (if it is not done already).

  • Right click our solution –> to Manage NuGet packages
  • Go to Installed packages –> Select Entity Framework –> Select Manage
  • Ensure you have a check for ChlodnyWebApi and DataAccess –> click OK
This entry was posted in Entity Framework, MVC, Web and tagged , , , , . Bookmark the permalink.

1 Response to Chlodny series Day 3: Connect Web Api to Entity Framework

  1. I constantly spent my half an hour to read this website’s articles every day along with a mug of coffee.

Comments are closed.