【问题标题】:MVC Invalid object name 'dbo.Staffs' errorMVC 无效的对象名称“dbo.Staffs”错误
【发布时间】:2015-11-12 06:37:56
【问题描述】:

我收到了错误Invalid object name 'dbo.Staffs'.,但我不知道为什么。实际上,我使用 EF 删除并重新创建了我的数据库,因为之前我遇到了其他错误。但我很确定我正确地重新创建了它,因为我已经为其他程序以相同的方式完成了它并且它工作正常。

.edmx 数据库图

控制器

    private StaffPortalDBEntities1 db = new StaffPortalDBEntities1();
    SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["StaffPortalDBConnectionString"].ConnectionString);

    [Authorize]
    public ActionResult Index()
    {
        var userEmail = User.Identity.Name;
        var model = db.Staffs.Where(i => i.Email == userEmail).Include("Histories").Include("CurrentApplications").FirstOrDefault();

        return View(model);
    }

我得到的错误是var model = db.Staffs.Where(i => i.Email == userEmail).Include("Histories").Include("CurrentApplications").FirstOrDefault();这一行

生成的 Staff 类

public partial class Staff
{
    public Staff()
    {
        this.Histories = new HashSet<History>();
        this.CurrentApplications = new HashSet<CurrentApplication>();
    }

    public int StaffID { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public Nullable<decimal> AllocatedLeave { get; set; }
    public Nullable<int> BalanceLeave { get; set; }

    public virtual ICollection<History> Histories { get; set; }
    public virtual ICollection<CurrentApplication> CurrentApplications { get; set; }
}

【问题讨论】:

  • 您的复数约定似乎有些问题。尝试在 Staff 类上方添加 [Table(Name = "Staff")] 属性。
  • @StuartLC 嗨,我试过了,但我仍然收到同样的错误 D:
  • 看起来您在某处歪曲了模型创建,智能感知是否为您提供了人员?你检查过模型吗?为什么要在当前应用程序的主键上使用这么多属性?

标签: sql-server asp.net-mvc entity-framework object


【解决方案1】:

试试这个:

var model = db.Staffs.Where(i => i.Email == userEmail).Include(x=>x.Histories).Include(x=>x.CurrentApplications).FirstOrDefault();

【讨论】:

  • 对于行 var model = db.Staffs.Where(i => i.Email == userEmail).Include("Histories").Include("CurrentApplications").FirstOrDefault();。即使我尝试了你的,我也会遇到同样的错误。当我尝试访问索引视图时,我得到它。
  • 检查您在索引视图中使用的模型。可能模型的名称是错误的。
  • 在我看来,我目前正在使用这个 [at] 模型 LeaveApplication.Models.CurrentAndHist 但由于我现在只是从我的控制器返回一个模型,我该使用什么? :O
  • 由于您使用的是“var model”,我不确定您的模型类型。找到它并通过 @using 在您的视图顶部添加类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多