'Cascading DropDownList in .NET Core
I am trying to use the tutorial linked below but adapting it to my SQL DB for States, Districts, Schools tables that I already have in place. I am new to .NET Core MVC and do not understand the error nor how to debug it. Any help appreciated.
Cascading DropDownList In .NET Core
Error: Microsoft.Data.SqlClient.SqlException: 'Invalid object name 'State'.' This exception was originally thrown at this call stack: [External Code] CascadingExample.Controllers.HomeController.Index() in HomeController.cs
[External Code]
using CascadingExample.Entities;
using CascadingExample.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace CascadingExample.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly MyDBContent _con;
public HomeController(ILogger<HomeController> logger, MyDBContent con)
{
_logger = logger;
_con = con;
}
public IActionResult Index()
{
ViewBag.StateList = _con.State.ToList();
return View();
}
public JsonResult GetDistrictByStateID(int statedID)
{
var data = _con.District.Where(x => x.StateID == statedID).ToList();
return Json(data);
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Solution 1:[1]
The error means the table named 'State' has not created or the Database you are referring has not created
I checked the dbcontext in your tutorial,and it will not create the table"State".
public class MyDBContent:DbContext
{
private IConfigurationRoot _config;
public MyDBContent(IConfigurationRoot config, DbContextOptions options) : base(options)
{
_config = config;
}
public DbSet<Category> Category { get; set; }
public DbSet<SubCategory> SubCategory { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(_config["ConnectionStrings:DefaultConnection"]);//connection string get by appsetting.json
}
}
You need to add these codes:
public DbSet<State> State { get; set; }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ruikai Feng |
