简体   繁体   中英

SqlException: Invalid object name ERROR WHILE BUILDING WEBSITE IN C# (VISUAL STUDIO) and sql server

New to WebDev, Tried to make a website where farmers can order medicines from stores online.

In a single solution, 2 projects were made Medicine.Model(The database was called here from the sqlsever) and Medicine.WEB(the above project is added here as a PROJECT REFERENCE )

3 Models

Farmer

using System;
using System.Collections.Generic;

#nullable disable

namespace Medicine.Model.Models
{
    public partial class Farmer
    {
        public Farmer()
        {
            Orders = new HashSet<Order>();
        }

        public string FarmerName { get; set; }
        public string Location { get; set; }
        public int Quantity { get; set; }
        public int FarmerId { get; set; }

        public virtual ICollection<Order> Orders { get; set; }
    }
}

Store

 public partial class Store
    {
        public Store()
        {
            Orders = new HashSet<Order>();
        }

        public int StoreId { get; set; }
        public string StoreName { get; set; }
        public string StoreLocation { get; set; }

        public virtual ICollection<Order> Orders { get; set; }
    }

Order(Stores the order details and links the above to tables)

public partial class Order
    {
        public int FarmerId { get; set; }
        public int StoreId { get; set; }
        public string Status { get; set; }
        public string DateOfOrder { get; set; }
        public int OrderId { get; set; }

        public virtual Farmer Farmer { get; set; }
        public virtual Store Store { get; set; }
    }

Made changes in the shared layout view to add the 3 controllers.

Made 3 controllers respectively

here is the shared layout code

<li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Farmers" asp-action="Index">Farmers</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Orders" asp-action="Index">Orders</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Store" asp-action="Index">Stores</a>
                        </li>

OK, so the problem is that the website runs perfectly fine when i click on home but when i click farmer in website then it shows the following error.

An unhandled exception occurred while processing the request. SqlException: Invalid object name 'Farmer'. Microsoft.Data.SqlClient.SqlCommand+<>c.b__169_0(Task result)

//Error also shows redline here

Medicine.WEB.Controllers.FarmersController.Index() in FarmersController.cs

        return View(await _context.Farmers.ToListAsync());

So i am adding the entire Farmer Controller Here,

FarmersController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Medicine.Model.Models;

namespace Medicine.WEB.Controllers
{
    public class FarmersController : Controller
    {
        private readonly MedicinesDBContext _context;

        public FarmersController(MedicinesDBContext context)
        {
            _context = context;
        }

        // GET: Farmers
        public async Task<IActionResult> Index()
        {
            return View(await _context.Farmers.ToListAsync());
        }

        // GET: Farmers/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var farmer = await _context.Farmers
                .FirstOrDefaultAsync(m => m.FarmerId == id);
            if (farmer == null)
            {
                return NotFound();
            }

            return View(farmer);
        }

        // GET: Farmers/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Farmers/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("FarmerName,Location,Quantity,FarmerId")] Farmer farmer)
        {
            if (ModelState.IsValid)
            {
                _context.Add(farmer);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(farmer);
        }

        // GET: Farmers/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var farmer = await _context.Farmers.FindAsync(id);
            if (farmer == null)
            {
                return NotFound();
            }
            return View(farmer);
        }

        // POST: Farmers/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("FarmerName,Location,Quantity,FarmerId")] Farmer farmer)
        {
            if (id != farmer.FarmerId)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(farmer);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!FarmerExists(farmer.FarmerId))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(farmer);
        }

        // GET: Farmers/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var farmer = await _context.Farmers
                .FirstOrDefaultAsync(m => m.FarmerId == id);
            if (farmer == null)
            {
                return NotFound();
            }

            return View(farmer);
        }

        // POST: Farmers/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var farmer = await _context.Farmers.FindAsync(id);
            _context.Farmers.Remove(farmer);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool FarmerExists(int id)
        {
            return _context.Farmers.Any(e => e.FarmerId == id);
        }
    }
}

Can someone please tell me where my mistake is and how to correct it?

Got it, See the models were made in the code from the database(sql server) so NuGet package console no error, the error was in connections string that we enter in appsetting.json, Thanks all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM