简体   繁体   中英

Error: An exception of type 'System.ArgumentException' occurred in System.Data.dll but was not handled in user code

I am just a newbie to MVC and learning through online tutorial. In my code, I am just retrieving data from the database using entity framework. I added [Key] attribute in model but still I faced that exception error. What else should i have to do to run the application? Really, need help!

Controller:

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>

try it like this

try{
    EmployeeContext employeecontext = new EmployeeContext ();
    Employee employee = employeecontext.Employees.Where( e=> e.ID == id ).First();
}
catch (Exception ex)
{
    Console.Writeline ("Exception: " + ex.toString());
}

And Post the output here please. Oh and don't forget to check if you have a table called "tbl_employee" with correct columns in your "nhphealthnew1" database

iam following the same tutorial and ia also faced this problem and i find the solution by adding this cod at web.config by this way

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM