Today I will explain how to install entity framework core in your ASP.NET MVC core 3.0 application with an empty template. Entity Framework Core, also called EF Core, is a complete rewrite from the ground up. If you have any experience with previous versions of Entity Framework, you will find a lot of familiar features.
What is EF core?
EF Core is an ORM (Object-Relational Mapper). EF core is lightweight, extensible, and open-source software. Like .NET Core, EF Core is also cross-platform. It works on Windows, Mac OS, and Linux. EF core is Microsoft’s official data access platform.
What is ORM?
ORM stands for Object-Relational Mapper and it enables developers to work with a database using business objects. As a developer we work with the application business objects and the ORM generates the SQL that the underlying database understands. In short, an ORM eliminates the need for most of the data-access code that developers usually need to write
EF Core Code First Approach
EF Core supports both the Code First approach and the Database First approach. However, with the Database First approach, there is very limited support in EF core at the moment.
Step 1. Startup Visual Studio 2019. Choose ASP.NET Core Web Application and click on “Next”
After clicking next, another wizard will open. Under the project name, give a meaningful name to your project and click on create.
That will open up another new wizard select ASP.Net Core 3.0 from the dropdown. If not, select default. Choose an empty template and click on create which will create your first ASP.Net Core Application.
Step 2. Click on tools select Nuget Package manager then click on Manage Nuget Package for solution. Now click on the browse tab then search the following package and install them.
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.Relational
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore.SqlServer
Step 3. Now create a folder Models under your project and create Employee class and EmployeeDbContext class.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace MvcCoreApplication.Models
{
public class Employee
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Please enter first name")]
[Display(Name = "First Name")]
[StringLength(100)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please enter last name")]
[Display(Name = "Last Name")]
[StringLength(100)]
public string LastName { get; set; }
[Required(ErrorMessage = "Please choose gender")]
[StringLength(10)]
public string Gender { get; set; }
[Required(ErrorMessage = "Please enter age")]
public int Age { get; set; }
[Required(ErrorMessage = "Please enter position")]
[StringLength(100)]
public string Position { get; set; }
[Required(ErrorMessage = "Please enter office")]
[StringLength(100)]
public string Office { get; set; }
[Required(ErrorMessage = "Please enter first name")]
public int Salary { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace MvcCoreApplication.Models
{
public class EmployeeDbContext : DbContext
{
public EmployeeDbContext(DbContextOptions options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
}
}
Step 4. Now open the appsettings.json file and add connect how we use set the connection in web config file. Similarly here you need to setup connect string.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "server=(localdb)\\MSSQLLocalDB;database=DemoDB;Trusted_Connection=true"
}
}
Step 5. Visual Studio 2019 generates program and startup classes. Now open the startup file and configure ASP.Net MVC Core Application development. Under app.UseEndpoints method just map endpoints.MapControllerRoute. Add connection middleware in services.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MvcCoreApplication.Models;
namespace MvcCoreApplication
{
public class Startup
{
private readonly IConfiguration Configuration;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
// Add MVC Middleware
services.AddControllersWithViews();
// Add Connection Middleware
services.AddDbContext<EmployeeDbContext>(
options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
// Add MVC Default route
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
});
}
}
}
Step 6. Now go to tools select nuget package manage than click on package manager console. It will bring console window below in visual studio 2019. Now write the following commands to enable migration.
- enable-migrations
- add-migration InitialModel (add migration can be anything you wish to)
- update-database
Here is the complete code.