尝试从我的数据库填充列表,如下所示,这是控制器:
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;
这是公园模型:
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; }
}
}
这里是TimetableSystemEntities模型:
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; }
}
}
但是当我调试并移动到可用性页面时,我收到了这个错误:
[System.Data.SqlClient.SqlException] {“无效的对象名称'dbo.ParkModels'。”}
不知道这里发生了什么,因为我在项目或数据库的任何地方找不到'ParkModels',模型是ParkModel,数据库表是Park。
答案 0 :(得分:1)
我对代码优先的理解是按照惯例,模型和表名需要匹配。在您的情况下,他们不需要指定映射。
[Table("Park")]
public class ParkModel
{
[Key]
public int ParkID { get; set; }
public string ParkName { get; set; }
}
然后你的背景应该是:
DbSet<ParkModel> Parks { get; set; }