Database Issue - An error occurred while executing the command definition. See the inner exception for details

.net c# entity-framework sql-server tsql

Question

Here is the controller that I'm trying to use to populate the lists from my database:

namespace TimetableSystem.Controllers
{
public class AvailabilityController : Controller
{
    TimetableSystemEntities systemDB = new TimetableSystemEntities();

    public ActionResult Index()
    {

        var parkList = new List<String>();
        var parkQry = from p in systemDB.Parks
                      orderby p.ParkID
                      select p.ParkName;
        parkList.AddRange(parkQry);
        ViewBag.Park = parkList;

The park model is shown below:

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace TimetableSystem.Models
{
    public class ParkModel
    {
        [Key]
        public int ParkID { get; set; }
        public string ParkName { get; set; }
    }
}

The TimetableSystemEntities model is seen here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace TimetableSystem.Models
{
    public class TimetableSystemEntities : DbContext
    {
        public TimetableSystemEntities() : base("DefaultConnection") { }

        public DbSet<Department> Departments { get; set; }
        public DbSet<Module> Modules { get; set; }
        public DbSet<Request> Requests { get; set; }
        public DbSet<Round> Rounds { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<ParkModel> Parks { get; set; }
        public DbSet<BuildingModel> Buildings { get; set; }
        public DbSet<RoomModel> Rooms { get; set; }
    }
}

However, I encounter the following issue when I debug and switch to the Availability page:

[System.Data.SqlClient.SqlException] 'dbo.ParkModels' is an invalid object name.

I'm not sure what's going on because the model is called ParkModel and the database table is called Park, but neither the project nor the database contain anything called "ParkModels."

1
0
11/24/2016 8:03:23 AM

Popular Answer

According to my understanding of code-first, the model and table names must coincide by convention. They don't in your situation, thus you must provide the mapping.

[Table("Park")]
public class ParkModel
{
    [Key]
    public int ParkID { get; set; }
    public string ParkName { get; set; }
}

Your context should then be:

DbSet<ParkModel> Parks { get; set; }
1
3/29/2014 4:09:52 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow