System.Core 中出现类型 'System.invalidOperationException' 的异常.dll但未在用户代码中处理



所以我在这里一步一步地按照教程进行操作,无法摆脱这个异常。我的连接字符串看起来正常。教程中没有发生这种情况,所以我不知道出了什么问题。 它把我带到了这一行 员工雇员 = 雇员上下文.雇员.单(emp => emp.员工ID == 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>

员工上下文类

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; }
        }
    }

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

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

public class EmployeeContext : DbContext
{
    public EmployeeContext()
        : base("EmployeeContext")
    {
    }
    // DbSet's here
    publlic DbSet<Employee> Employees { get; set; }
}

相关内容

最新更新