Adding DBContext to an ASP.NET application

We just added the Todo model. Now, let's add DBContext to manage and persist Todo in the database. DBContext acts as a bridge between your classes and database. To add it, follow these steps:

  1. Right-click on the Models folder and navigate to Add | Class:
Add a class for DBContext under the Models folder
  1. Name the class as TodoContext and add the following code snippet to it:
   public class TodoContext : DbContext
{
public TodoContext(DbContextOptions<TodoContext>
options)
: base(options)
{
}
public DbSet<Todo> Todos { get; set; }
}

TodoContext helps you interact with the database and commits the changes as a single unit of work. TodoContext is configured to use the SQL Server, and the connection string is read from the config.json file that we will add in the next step.

 

  1. Add using statement to import Microsoft.EntityFrameworkCore in Startup.cs.
  2. Configure the SQL service by adding the following code snippet to the ConfigureServices method:
    services.AddEntityFrameworkSqlServer()   
.AddDbContext<TodoContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString
("DefaultConnection")));
services.AddMvc();
  1. Add an appsettings.json file to hold the value of the connection string and update it with this content:
 {   
"ConnectionStrings":
{
"DefaultConnection": "Server=(localdb)\mssqllocaldb;
Database=aspnet-CloudInsights-f2d509d5-468f-4bc9-
9c47-
0593d0907063;Trusted_Connection=True;
MultipleActiveResultSets=true"
},
"Logging":
{
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}

In this JSON file, we added the connect string under the data item.

Next, we will add and configure Entity Framework in our application. The complete code snippet of the Startup.cs file is as follows:

public class Startup   
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkSqlServer()
.AddDbContext<TodoContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.ContentRootPath, "node_modules")
),
RequestPath = "/" + "node_modules"
});
app.UseMvc();
}
}

In the Startup.cs constructor, we built the configuration to read from the config.json file. In the ConfigureServices method, we added Entity Framework and hooked the SQL Server and TodoContext to it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset