我只是 MVC 的新手,通过在线教程学习。在我的代码中,我只是使用实体框架从数据库中检索数据。我在模型中添加了
[Key]
属性,但仍然遇到该异常错误。我还应该做什么才能运行该应用程序?真的,需要帮助!
控制器:
public class EmployeeDetailsController : Controller
{
public ActionResult details(int id)
{
EmployeeContext employeecontext = new EmployeeContext();
Employee employee = employeecontext.Employees.Single(emp => emp.emp_id == id);
return View(employee);
}
}
Employeecontext.cs
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
员工.cs:
[Table("tbl_employee")]
public class Employee
{
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int emp_id { get; set; }
public string emp_name { get; set; }
public string emp_email { get; set; }
}
查看(details.cs.html):
....
<h2> Employee Details</h2>
<div>
Customer id : @Model.emp_id
Customer name : @Model.emp_name
Customer email : @Model.emp_email
</div>
Web.config:
<connectionStrings>
<add name="EmployeeContext"
connectionString="Data Source=192.168.4.201;Initial Catalog=nhphealthnew1;User ID=teamaardee;Password=team@aardee#1234#!"
providerName="System.Data.SqlClient" />
</connectionStrings>
像这样尝试一下
try{
EmployeeContext employeecontext = new EmployeeContext ();
Employee employee = employeecontext.Employees.Where( e=> e.ID == id ).First();
}
catch (Exception ex)
{
Console.Writeline ("Exception: " + ex.toString());
}
请在此处发布输出。 哦,不要忘记检查您的“nhphealthnew1”数据库中是否有一个名为“tbl_employee”的表,其中包含正确的列