find and solve || findandsolve.com
Please wait.....

Welcome back.






Before Read Terms of use

Connection String in Appsettings.json ASP.NET Core-Connect to Database


Open your visual studio 2015 or grater then 2015 and select File > New > Project.After selecting the project, a new project dialog will open in your computer given below image.Select .NET Core  Web  Application inside Visual C# menu from the left panel given.Then,select ASP.NET Core Web Application from available project types list and then Put the name of the project as "ConnectionDatabase" and press OK.


asp.net core connection in sql database example

Setup 2:

After clicking on OK button,a new dialog will open your computer and asking you to select the project template form listing different template.Then you can see there  are two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.2” or grater then core version 2.2  from these dropdowns and select  “Web Application (Model-View-Controller)”  template and press OK Button.

how to connect asp.net core in sql server


Setup:3

Now, our project will be created. You can see the folder structure in Solution Explorer as shown in the given below image.

sql connection in asp.net core 3.0


Now you can see above image "Controller","Model" and "View" How to work MVC in asp.net? you can see for more details about MVC to Click here 

Setup :4
We are using Entity Framework core for "Code first" approach to create our models.First you should create New Folder under project solution. Right click on your project solution  and select Add > New Folder.Name your folder  "Entities"  as given below image.

how to connection in sql with asp.net core version 2.0



Setup :5

After Add Entities folder under your project solution then  again righ click on your  "Entities" folder and select Add > Class. Name your Connection Class  "DatabaseContext.cs" and click Add button. And also add your entity model  as same folder[Entity model is represent sql Table]. At this point of time, the Entities folder will have the following structure.


asp.net core example with crud operation




Setup :6

After Added  "DatabaseContext.cs" Class under Entities folder then open your "DatabaseContext.cs" File and past  code on "DatabaseContext.cs" class which is give below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace ConnectionDatabase.Entities
{
    public class DatabaseContext : DbContext
    {
        private IConfigurationRoot _config;
        public DatabaseContext(IConfigurationRoot config, DbContextOptions options) : base(options)
        {
            _config = config;
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer(_config["ConnectionStrings:DefaultConnection"]);
            //connection string get by appsetting.json
        }
    }
}

Setup:7

After Past this  code in your DatabaseContext.cs class and the open your appsettings.json

Lest know about appsettings.json
Before asp.net core The connectionString is define in your web.config like that
  <connectionStrings>   
    <add name="DatabaseContext" connectionString="data source=YourDatabaseServerName;Initial Catalog=YourDatabaseName;
      user id=YouserUserId;password=YourPassword" providerName="System.Data.SqlClient" />    
  </connectionStrings>

After in asp.net core,the connectionString proparties are added in appsetting.json file.
All of the application's settings are contained in a file named appsettings.json. Any changes to the appsettings.json file will require restarting the "Microsoft IIS Administration" service to take effect.
The appsettings.json file is located at: %SystemDrive%\Program Files\IIS Administration\<version>\Microsoft.IIS.Administration\config\appsettings.json

Open your appsetting.json an put this code in appsetting.json file as given below
{
    "ConnectionStrings": {
      "windowsAuthentication": true,
      "DefaultConnection": "Data Source=sql-server-name;Database=database-name;Trusted_Connection=True;" 
      //this is windows athenticaiton
      //"SqlAuthintication": "Server=SQ-9KQH8Q0;Database=abc;User ID=server;
      //Password=password120;Trusted_Connection=True;Connection Timeout=30;"
    },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Step :8

Open Startup.cs and put the following code as a given image.

CRUD in asp.net core with step by step


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ConnectionDatabase.Entities;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ConnectionDatabase
{
    public class Startup
    {
        private IConfigurationRoot _config;
        public Startup(IHostingEnvironment env)
        {
            var ConfigBuilder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
                        .AddJsonFile("appsettings.json");
            _config = ConfigBuilder.Build();
        }
        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.Configure<CookiePolicyOptions>(options =>
            {
                services.AddSingleton(_config);
                services.AddDbContext<DatabaseContext>();
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
              app.UseExceptionHandler("/Home/Error");
             // The default HSTS value is 30 days. You may want to change this for production scenarios, 
             //see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
After past above code in your Startup.cs file, your connection will be start in asp.net core.We are ready to Migration our project.EF Core migrations are a set of commands which you can execute in NuGet Package Manager Console or in dotnet Command Line Interface (CLI).

Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.

Comments



Report Response