For starters, we need to install Entity Framework and its tools to our Infrastructure project.
Follow these steps to create the EF context:
- Just right-click on dependencies and select Manage NuGet Packages.
- Afterwards write Microsoft.EntityFramework.Core.SqlServer in the search box and install it.
Your screen should look as follows:
- Similarly, install the Microsot.EntityFrameworkCore.Tools package, as follows:
So, your project folder for Infrastructure looks as follows:
- 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();
}
...
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.