简体   繁体   中英

error in Data access mvc using entity framework

Error message is :

Invalid column name 'EmployeeId' Invalid column name 'EmployeeId' Invalid column name 'City'.

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

But I got exact same database table with all matching columns, why it said I have invalid columns? where did I go wrong? I used codeFirst approach, and actually there are four columns in the table which are EmployeeID, Name, Gender, City, how come I don't have error in Name and Gender but just errors in EmployeeID and City? and error in EmployeeID appear twice?

Detail code

Employee class:

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; }
    }
}

EmployeeContext :

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

Database table: 在此处输入图片说明

Why do you decorate EmployeeContext using [Table("tblEmployee")]? Should you do that with Employee class instead, right?

[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; }
}

What I think is:

EmployeeContext employeeContext = new EmployeeContext();

That line is creating context against local database server. Please make sure you are giving correct connection string as a parameter:

EmployeeContext employeeContext = new EmployeeContext(connection-string);

Connection string should be taken from web.config or app.config depending on project you are working in.

The details you have provided is not good enough to understand your problem. First make sure you are properly connected to the database. Secondly, if City is navigation property in your entity class then maybe you are missing " Include " method.

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