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

问题描述 投票:0回答:2

我只是 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>
c# asp.net .net asp.net-mvc linq
2个回答
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”的表,其中包含正确的列


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

© www.soinside.com 2019 - 2024. All rights reserved.