For this tutorial, we'll use Entity Framework (EF) Code First to create the back-end database.
Web API OData does not require EF. Use any data-access layer that can translate database entities into models.
First, install the NuGet package for EF. From the Tools menu, select NuGet Package Manager > Package Manager Console. In the Package Manager Console window, type:
Install-Package EntityFramework
Open the Web.config file, and add the following section inside the configuration element, after the configSections element.
<configuration>
<configSections>
<!-- ... -->
</configSections>
<!-- Add this: -->
<connectionStrings>
<add name="ProductsContext" connectionString="Data Source=(localdb)\v11.0;
Initial Catalog=ProductsContext; Integrated Security=True; MultipleActiveResultSets=True;
AttachDbFilename=|DataDirectory|ProductsContext.mdf"
providerName="System.Data.SqlClient" />
</connectionStrings>
This setting adds a connection string for a LocalDB database. This database will be used when you run the app locally.
Next, add a class named ProductsContext to the Models folder:
using System.Data.Entity;
namespace ProductService.Models
{
public class ProductsContext : DbContext
{
public ProductsContext()
: base("name=ProductsContext")
{
}
public DbSet<Product> Products { get; set; }
}
}
In the constructor, "name=ProductsContext" gives the name of the connection string.