In this tutorial, we will see how to connect SQL database using Asp.net core.
Steps
- Create New Project
- Select ASP.net Core Web Application
- Select Location
- Select Web Application MVC (Model -> View -> Controller)
Add some necessary NuGet Packages
- Right Click On project
- Select Manage NuGet Packages
- Select these packages one by one Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Tools, Microsoft.Visual Studio.Web.CodeGeneration.Design
- Then Click Install
After that get the connection string and open appsetting.json at the root directory of the application.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"database": {
"connection": "Data Source=.;Initial Catalog=schoolDB;Trusted_Connection=True;"
},
"AllowedHosts": "*"
}
Open startup.cs at the root directory of the application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using sample.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace sample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<SchoolDBContext>(option => option.UseSqlServer(Configuration["database:connection"]));
services.AddMvc().AddXmlDataContractSerializerFormatters();
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}