【问题标题】:error in Data access mvc using entity framework使用实体框架的数据访问 mvc 中的错误
【发布时间】:2017-01-15 10:18:07
【问题描述】:

错误信息是:

列名“EmployeeId”无效 列名“EmployeeId”无效 列名“城市”无效。

{
   EmployeeContext employeeContext = new EmployeeContext();
   Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeId == id); //This line is causing the error
}

但是我得到了包含所有匹配列的完全相同的数据库表,为什么它说我有无效的列?我哪里做错了?我使用了codeFirst方法,实际上表中有四列是EmployeeID,Name,Gender,City,为什么我的Name和Gender没有错误,而EmployeeID和City只有错误? EmployeeID 中的错误出现了两次?

详细代码

员工类:

namespace MVCDemo.Models
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
    }
}

员工上下文:

namespace MVCDemo.Models
{
    [Table("tblEmployee")]
    public class EmployeeContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }
    }
}

数据库表:

【问题讨论】:

  • 您认为您连接到哪个数据库?您使用的是 DatabaseFirst 还是 CodeFirst 方法?
  • 显示您的 EmployeeContext 和 Employee 模型代码。
  • @abdul 已将其添加到我的帖子中

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


【解决方案1】:

为什么要使用 [Table("tblEmployee")] 来装饰 EmployeeContext?你应该用 Employee 类来代替,对吗?

[Table("tblEmployee")]
public class Employee
{
    public int EmployeeId { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public string City { get; set; }
}

【讨论】:

    【解决方案2】:

    我的想法是:

    EmployeeContext employeeContext = new EmployeeContext();
    

    该行正在针对本地数据库服务器创建上下文。请确保您提供正确的连接字符串作为参数:

    EmployeeContext employeeContext = new EmployeeContext(connection-string);
    

    连接字符串应取自 web.config 或 app.config,具体取决于您正在从事的项目。

    【讨论】:

    • 我认为我在 web.config 中得到了正确的本地数据库服务器,如果我更改数据库名称,我会得到另一个不同的错误,比如无效对象,但现在我得到了无效的列
    • 这是代码优先的方法。其实表中有四列EmployeeID,Name,Gender,City,为什么我的Name和Gender没有错误,而EmployeeID和City只有错误?
    【解决方案3】:

    您提供的详细信息不足以理解您的问题。首先确保您已正确连接到数据库。其次,如果 City 是实体类中的导航属性,那么您可能缺少“Include”方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      相关资源
      最近更新 更多