【问题标题】:I get the following error in mvc4,'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll我在 mvc4 中收到以下错误,EntityFramework.SqlServer.dll 中发生'System.Data.Entity.Core.EntityCommandExecutionException'
【发布时间】:2015-12-21 16:26:29
【问题描述】:

我在该行中收到以下错误

Employee employee = employeeContext.Employees.Single(x => x.EmployeeId==id)

类型异常 'System.Data.Entity.Core.EntityCommandExecutionException' 发生在 EntityFramework.SqlServer.dll 但未在用户代码中处理

我的控制者是

public class EmployeeController : Controller
{
    //
    // GET: /Employee/

    public ActionResult Index()
    {
        return View();
    }
    public ActionResult Details(int id)
    {
        EmployeeContext employeeContext = new EmployeeContext();
        Employee employee = employeeContext.Employees.Single(x =>x.EmployeeId==id); 

        return View(employee);
    }

}

模型类是:

[Table("tblEmployee")]
public class Employee
{
    public int EmployeeId { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public string City { get; set; }
}

上下文类是:

【问题讨论】:

  • 这个错误可能有很多原因——例如,连接字符串是否正确。此外,具有特定 id 的员工是否存在。尝试验证连接字符串,并使用“SingleOrDefault”而不是“Single”。您可能首先需要尝试找出导致问题的确切错误。
  • 您的员工类似乎没有正确绑定数据库表,比较表和模型类的属性和类型。

标签: c# entity-framework asp.net-mvc-4


【解决方案1】:

通过改变来试试这个

Employee employee = employeeContext.Employees.Single(x =>x.EmployeeId==id); 

进入

Employee employee = employeeContext.Employees.Where(x =>x.EmployeeId==id).FirstOrDefault; 

【讨论】:

  • 他为什么要这样做?
  • 我认为.FirstOrDefault 是一种方法而不是一种属性!
  • 对不起...我想念那个...试试 employeeContext.Employees.Where(x =>x.EmployeeId==id).FirstOrDefault();
猜你喜欢
  • 1970-01-01
  • 2014-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多