Create EF Context and Migrations

For starters, we need to install Entity Framework and its tools to our Infrastructure project.

Follow these steps to create the EF context:

  1. Just right-click on dependencies and select Manage NuGet Packages.
  2. Afterwards write Microsoft.EntityFramework.Core.SqlServer in the search box and install it.

Your screen should look as follows:

  1. Similarly, install the Microsot.EntityFrameworkCore.Tools package, as follows:

So, your project folder for Infrastructure looks as follows:

  1. Next, we create the EF folder in the Infrastructure project and implement our DbContext with a class called RestBuyContext. Make sure you have a reference to the RestBuy project from Infrastructure. Use this code:

Go to https://goo.gl/wYLwRA to access the code.
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using RestBuy.Entities;
using System;
using System.Collections.Generic;
using System.Text;
...
void ConfigureStockAmount(EntityTypeBuilder<StockAmount> builder)
{
...
builder.Property(ci => ci.Quantity).IsRequired().IsConcurrencyToken();
}
...
In the preceding mapping, the Quantity property of StockAmount is marked as ConcurrencyToken as we don't want two orders to reduce the stock amount simultaneously. Suppose that we have two parallel requests racing to buy for the last item. Only one of them can win. Using ConcurrencyToken causes Entity Framework to generate a query that confirms that the value has not been changed. Doing so will cause DbUpdateConcurrencyException; in this case, we have to retry.

Here we use a HiLo algorithm for key generation. If you don't make use of HiLo, normally EF and SQL server uses auto incremented IDs. While auto incremented IDs are simpler, whenever you add an entity to the context, this addition forces the entity to be inserted to the database. That is because we can only retrieve the ID if the actual insertion happens in the case of auto incremented IDs. The HiLo algorithm frees us from this restriction by reserving the IDs beforehand using a database sequence. We also change the defaults for the sequence so that it starts from 1,000 and increments by 100 for each. By using this approach we can insert our design time data to the first 1,000 slots available.