These steps will show how to create or update Database with Code First Approach using .NET Core EF Framework.
- Install Packages from Nuget.
You need to install following packages- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore.SqlServer
- Make sure SDK Version and Package versions are matched.
This is not really required but recommended.- Check enable .net core SDKs
Open the Command Line or PowerShell window
type following command.
dotnet –info
- Check enable .net core SDKs
- Create Context
In my example, the context name will be ‘StoreContext’.public class StoreContext : DbContext { public StoreContext(DbContextOptions<StoreContext> options) : base(options) { } public DbSet<Product> Products { get; set; } }
public class Product { public int Id { get; set; } public string Name { get; set; } }
By default, if entity framework has int Id, this field will be generated as primary key and auto incremental Id.
- Add connection string on AppSettings.json file.
"ConnectionStrings": { "DefaultConnection": "Data Source=localhost;Initial Catalog=WebStore;Persist Security Info=True;User ID=<userId>;Password=<password>" }
- Add that connection string into ConfigureService() method in StartUp.cs file.
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //Need to add this line for the DB Connection. services.AddDbContext<StoreContext>(x => x.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"))); // Register the Swagger services services.AddSwaggerDocument(); }
- Create the migration script.
Open the Command Line or PowerShell window and set the directory to your project.
type following command
dotnet ef migrations add <migrationName as you want> -0 <Folder that you want to create>This is my example:dotnet ef migrations add InitialCreate -o Data/Migrations
This will create following files on under Data/Migrations folder.
- Update database.
Execute following command.
dotnet ef database update.Note: If the user has permission to create the database on DB server, this will create the database as well.