【发布时间】: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