How to implement EF Core

Implementing EF in the .NET CORE environment it a little bit different from .NET Framework. You start by installing EF CORE by using Nuget package Manager, Microsoft.EntityFrameworkCore.SqlServer. In the Startup.cs ensure that the using statement using Microsoft.EntityFrameworkCore; is written. In the Models folder create a class which represents an exact copy of the SQL Table. You can add classes in this folder for all tables involved in your project.
public partial class Employee { public int ID { get; set; } [Required] public int WorkNo { get; set; } public string Name { get; set; } . . . }
Following line should be added in the appsettings.json
{ . . . "ConnectionStrings": { "FpcDb": "data source=JO-LENOVO\\SQL2014;initial catalog=FPC_DB;integrated security=True;" } }
Create a Data folder in your project and add the following file called FPC_Emp_Context.cs with this code:
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MyCoreMvc.Models; namespace MyCoreMvc.Data { public class FPC_Emp_Context: DbContext { public FPC_Emp_Context(DbContextOptions options) : base(options) { } public DbSet<Employee> FPC_Employees { get; set; } } }
Add following code in startup.cs :
public void ConfigureServices(IServiceCollection services) { . . . services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddDbContext<FPC_Emp_Context>(options => options.UseSqlServer(Configuration.GetConnectionString("FpcDb"))); }
in a given Controller the following could be implemented in the Controller class itself and in the constructor:
public class HomeController : Controller { private readonly FPC_Emp_Context _Efcontext; public HomeController(FPC_Emp_Context context) { _Efcontext = context; } . . . }
In another place in the controller class you can use EF this way:
using Microsoft.EntityFrameworkCore; using MyCoreMvc.Data; using MyCoreMvc.Models; //Ensure that the above namespaces are referred to in your Controller class. public async Task Index() { return View(await _Efcontext.FPC_Employees.ToListAsync()); }