Home > Enterprise >  Trying connect SQL Server and ASP.NET MVC mvc app
Trying connect SQL Server and ASP.NET MVC mvc app

Time:01-06

I'm trying to create a Stock Tracking System with ASP.NET MVC and I created a database with SQL Server but I can't connect this from my app.

When I try to start. VS is giving me this error can anyone help me?

enter image description here

Here are my Program.cs and DBContext.cs files

Program.cs:

using Microsoft.EntityFrameworkCore;
using stockTrackingSystem.Data;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    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.UseRouting();

app.UseAuthorization();

//DB CONNECTION
var connectionString = builder.Configuration.GetConnectionString("AppDb");

builder.Services.AddDbContext<DBContext>(x => x.UseSqlServer(connectionString));

DBContext.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.EntityFrameworkCore;
using stockTrackingSystem.Models;

namespace stockTrackingSystem.Data
{
    public class DBContext: DbContext
    {
        public DbSet<Store> Store { get; set; }
        public DbSet<Category> Category { get; set; }
        public DbSet<Costumer> Costumer { get; set; }
    }
}

CodePudding user response:

Modify your DBContext class to include a constractor.

public class DBContext: DbContext
{
    public DBContext(DbContextOptions<DBContext> options)
        : base(options)
    {
    }

    public DbSet<Store> Store { get; set; }
    public DbSet<Category> Category { get; set; }
    public DbSet<Costumer> Costumer { get; set; }
}
  • Related