Monthly Archives: December 2016

Entity Framework Scaffold DBContext (ASP.NET Core)

Steps:

– Install EF:

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Install-Package Microsoft.EntityFrameworkCore.Tools –Pre
Install-Package Microsoft.EntityFrameworkCore.Design
Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

– Add to project.json

 "tools": {
   "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0-preview3-final",
   "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
   "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
 },

– From “NuGet Package Manager” then “Package Manager Console”

Scaffold-DbContext "Server=;Database=;user id=;password=;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=False" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

– Update appsettings.json to include the connection string..

  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=devsql01;Database=nasr_scratch;user id=dev;password=Automation15;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=False;"
    } 
  },

– Add the DbContext to the Startup.cs using the connection string..

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.            
            services.AddMvc();
            services.AddDbContext(
                o => o.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }

Update the Context:

public class MyContext : DbContext
{
    public MyContext(DbContextOptions options)
      :base(options)
    { }
}

– Create your controller. For Instance; BulkTagCreationController. You can now reference the context using DI.

    [Route("api/configuration/[controller]")]
    public class BulkTagCreationController : Controller         
    {
        public readonly nasr_scratchContext _context;

        public BulkTagCreationController(nasr_scratchContext context)
        {
            _context = context;
        }