首先,请原谅我,但是当谈到ASP.NET时我总是新手,因为我现在正在尝试学习它的一些内容。ASP.NET MVC无法从本地SQL Server Express数据库中检索数据
我正在关注ASP.NET MVC4的在线教程之一,但我正在使用Visual Studio 2015社区(MVC5)和SQL Server 2014 Express。
目标是使用Windows身份验证从本地SQL Server Express数据库检索数据。在这种情况下,雇员的身份,姓名,城市和性别。这时我收到以下错误:
An exception of type 'System.Data.Entity.Core.EntityException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: The underlying provider failed on Open.
数据库看起来是这样的 - ID作为int
,其余为varchar(50)
:
Employee.cs
位于型号:
[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; }
}
EmployeeContext.cs:
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
EmployeeController.cs:
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);
}
}
视图 - Details.cshtml:
@model MVCDemo.Models.Employee
@{
ViewBag.Title = "Employee Details";
}
<h2>Employee Details</h2>
<table style="font-family:Arial">
<tr>
<td>
<b>Employee ID:</b>
</td>
<td>
@Model.EmployeeId
</td>
</tr>
<tr>
<td>
<b>Name:</b>
</td>
<td>
@Model.Name
</td>
</tr>
<tr>
<td>
<b>Gender:</b>
</td>
<td>
@Model.Gender
</td>
</tr>
<tr>
<td>
<b>City:</b>
</td>
<td>
@Model.City
</td>
</tr>
</table>
最后,来自web.config
在根连接字符串(I制成肯定)目录:
<add name="EmployeeContext"
connectionString="Data Source=DESKTOP-6RQ94N9\MAIN;Initial Catalog=Sample;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
默认connectionString="Data Source=.\SQLEXPRESS;
根本没有工作。 无论如何,服务器资源管理器显示与数据库的成功数据连接,我可以浏览Visual Studio中的表及其列。
当我启动该项目,并尝试例如:
http://localhost/MVCDemo/Employee/Details/1
该网站只是不断加载了一段时间,然后在上面提到的例外发生在
Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeId == id);
当我调试应用程序, employeeContext.Employees.Local.Count
显示0,所以我猜没有数据正在检索。
非常感谢您的帮助!
检查它在Sql Server配置管理器中,我确实已将服务器名称更改为MAIN。此时,连接字符串如下所示:''但仍然没有结果。 –
Dandry
您使用什么名称从Visual Studio Server Explorer访问它? – Alex
我正在使用./MAIN服务器,然后从下拉列表中选择我的'Sample'数据库。一切正常。在VS中,我可以轻松浏览表格数据。我也用'base(“EmployeeContext”)创建了这个空构造函数。没有变化。 – Dandry