C# Class Project using Visual Studio Code and .NET Core 2.2
This project will list, create, update and delete an employee.
To install the Entity Framework Core, open the project folder in the terminal and run the command below:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
To execute the dotnet ef command, install the package below:
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet tool install —global dotnet-ef —version 2.2.6
Create the Employee abstract class inside the Classes\Entities folder:
namespace CSharpClassProject.EfCore.Classes.Entities
{
public abstract class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string CompanyName { get; set; }
}
}
Create the Developer class inheriting from the Employee class inside the Classes\Entities folder:
namespace CSharpClassProject.EfCore.Classes.Entities
{
public class Developer : Employee
{
}
}
Create the IContext interface in the Interfaces folder:
using CSharpClassProject.EfCore.Classes.Entities;
using Microsoft.EntityFrameworkCore;
namespace CSharpClassProject.EfCore.Interfaces
{
public interface IContext
{
DbSet<Developer> Developers { get; set; }
}
}
Then in the Classes\Entities folder, create the Context class inheriting from the DbContext class, responsible to the database context, and implements the IContext interface created above:
using CSharpClassProject.EfCore.Interfaces;
using Microsoft.EntityFrameworkCore;
namespace CSharpClassProject.EfCore.Classes.Entities
{
public class Context : DbContext, IContext
{
public DbSet<Developer> Developers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Configures the database connection string
optionsBuilder.UseSqlServer("<connection string>");
}
}
}
Now, build the project and then create the initial migration:
dotnet ef migrations add InitialMigration
A Migration folder will be created with tree files (the 20200523165930 is the time when you ran the dotnet ef migrations command):
Then, run the command below to update the database:
dotnet ef database update
To see the entire command that will be executed in the update, add the —verbose parameter:
dotnet ef database update —verbose
To revert some change, execute the comand below:
dotnet ef database update \
https://docs.microsoft.com/en-us/ef/core/get-started/install/
https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings
https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet