【问题标题】:An exception of type 'System.invalidOperationException' occures in System.Core.dll but was not handled in user codeSystem.Core.dll 中出现“System.invalidOperationException”类型的异常,但未在用户代码中处理
【发布时间】:2019-01-23 04:17:49
【问题描述】:

所以我在这里一步一步地遵循教程,无法摆脱这个异常。我的连接字符串看起来不错。它不会在教程中发生,所以我不知道出了什么问题。 它把我带到了这一行 Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeId == id);

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ATSTest.Models;


namespace ATSTest.Controllers
{
    public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Details(int id)
        {
            EmployeeContext employeeContext = new EmployeeContext();
            Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeId == id);

            return View(employee);
        }
    }
}

这是我的课

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace ATSTest.Models
{   
    [Table("Employees")]
    public class Employee
    {

        public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string HiredDate { get; set; }
    }
}

连接字符串

<connectionStrings>
    <add name ="EmployeeContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=AssetTracking;Integrated Security=True" providerName="System.Data.SqlClient" />

  </connectionStrings>

EmployeeContext 类

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace ATSTest.Models

    {
        public class EmployeeContext : DbContext
        {
            public DbSet<Employee> Employees { get; set; }
        }
    }

【问题讨论】:

  • 你检查数据库表Employees是否创建了吗?
  • 是的,我的 Sql Server 中有一个名为Employees 的表,据我所知,我将确切的连接字符串正确复制到了Web.config 中。
  • 您是否在 EmployeeContext 类中正确使用了此连接字符串?该类的代码不在此处。
  • 据我所知。我编辑了我的帖子以显示 EmployeeContext 类。如果您发现任何问题,请告诉我

标签: c# sql-server


【解决方案1】:

您的问题的答案是您没有使用连接字符串。

您必须传递连接字符串名称,如下例所示。

public class EmployeeContext : DbContext
{
    public EmployeeContext()
        : base("EmployeeContext")
    {

    }

    // DbSet's here
    publlic DbSet<Employee> Employees { get; set; }
}

【讨论】:

  • 它现在给了我这个错误。 System.InvalidOperationException: Sequence 不包含任何元素,这让我回到了它之前所做的同一行。员工员工 = employeeContext.Employees.Single(emp => emp.EmployeeId == id);
  • 那是因为您在员工中没有任何数据。使用 SingleOrDefault 方法而不是 Single。这将返回 null 而不是抛出异常。
  • 请参考documentation 了解如何为测试目的播种数据。
  • 我的员工表中有数据。谢谢,不过我想我会看看那个微软教程。
  • 如果您有数据,那么 where 子句 id 可能与表中的任何数据都不匹配。请使用存在数据的 ID。另外,如果它解决了您的问题,建议将其标记为答案... ;)
猜你喜欢
  • 1970-01-01
  • 2017-04-18
  • 2018-10-25
  • 2015-05-30
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多