错误:System.Data.dll中发生类型为“System.ArgumentException”的异常,但未在用户代码中处理

时间:2017-02-22 06:45:16

标签: c# asp.net .net asp.net-mvc linq

我只是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; }
}

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

view(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>

2 个答案:

答案 0 :(得分:0)

尝试这样

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”的表格,其中包含正确的列

答案 1 :(得分:0)

iam遵循相同的教程,ia也遇到了这个问题,我通过在 web.config 上以这种方式添加此cod来找到解决方案

  <connectionStrings>
  <add name="EmployeeContext"  
        providerName="System.Data.SqlClient"  
        connectionString="Server=.\SQLEXPRESS;Database=Sample;Integrated Security=True;"/>
</connectionStrings>

enter image description here