In an ASP.NET MVC web application, I have created the following entity:
[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; }
}
But, when I try to retrieve data from a database table called tblEmployee using Entity Framework, I get an error. What I have done until now is:
- Created a database
MVCDemowith "." as server name and using Windows authentication containing a table calledtblEmployee - Installed Entity Framework
- Added
EmployeeContext.csclass file toModelsfolder
Code:
namespace MVCDemo.Models
{
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
}
Added a connection string to web.config file in the root directory
<connectionSrtings> <add name="EmployeeContext" connectionString="server=.; database=MVCDemo; integrated security=SSPI" providerName="System.Data.SqlClient;" /> </connectionSrtings>Added Details actionResult to EmployeeController to show employee details:
namespace MVCDemo.Controllers { public class EmployeeController : Controller { // GET: Employee public ActionResult Details(int id) { EmployeeContext employeeContext = new EmployeeContext(); Employee employee = employeeContext.Employees.Single(e => e.EmployeeId == id); return View(employee); } } }
Finally, I added the following code to Global.asax to prevent initialization:
Database.SetInitializer<MVCDemo.Models.EmployeeContext>(null);
The problem is when I run the application I get this error:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
and when I comment connection strings out and try to reach
http://localhost:60613/Employee/Details/1
to show details of 1st employee, I get this error:
System.Data.Entity.Core.EntityException: 'The underlying provider failed on Open.'SqlException: Cannot attach the file 'C:\Users\arya\source\repos\MVCDemo\MVCDemo\App_Data\MVCDemo.Models.EmployeeContext.mdf' as database 'MVCDemo.Models.EmployeeContext'.