【问题标题】:Error: An exception of type 'System.ArgumentException' occurred in System.Data.dll but was not handled in user code错误:System.Data.dll 中出现“System.ArgumentException”类型的异常,但未在用户代码中处理
【发布时间】:2017-02-22 06:45:15
【问题描述】:

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

查看(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>

【问题讨论】:

  • 调试你的代码!哪一行代码抛出了异常,异常的细节是什么。
  • Employee.cs: 是 EF 的自动生成类吗?
  • 在 Employeedetailscontroller 中调试代码后出现错误,“Employee employee = employeecontext.Employees.Single(emp => emp.emp_id == id);”错误:'System.Data 类型的异常.Entity.Core.EntityCommandExecutionException'发生在 EntityFramework.SqlServer.dll 中,但未在用户代码中处理附加信息:执行命令定义时出错。有关详细信息,请参阅内部异常。
  • @M Adeel Khalid,先生,我创建了我定义字段的那个类。
  • 也提供内部异常细节。注意 EF 列名和属性约束,它们需要与数据库属性同步。

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


【解决方案1】:

这样试试

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

【讨论】:

  • @Elvin No Matter 好的,我会试试这个..!!!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多