c# - 连接到数据库失败。检查连接字符串是否正确以及 DbContext 构造函数

标签 c# sql-server asp.net-mvc entity-framework

访问数据库时发生错误。这通常意味着与数据库的连接失败。检查连接字符串是否正确,是否使用适当的 DbContext 构造函数来指定它或在应用程序的配置文件中找到它。

我发誓我什么都试过了!完成本教程并努力连接到数据库。

我在 SQL Server 2012 中的表名为“tblEmployee”,数据库名为“Sample”

这是 Employee.cs 类

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

这是员工上下文模型类

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

这是员工 Controller

public class EmployeeController : Controller
{
    public ActionResult Details()
    {
        EmployeeContext employeeContext = new EmployeeContext();
        Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeID == 2);
        return View(employee);
    }
}

这是 web.config 文件

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameters>
        <parameter value="v11.0" />
    </parameters>
   </defaultConnectionFactory>
    <providers>
    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
</entityFramework>

这是连接字符串

<connectionStrings>
    <add name="EmployeeContext" connectionString="Data Source=ADMIN-PC;Initial Catalog=Sample;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
</connectionStrings>

实际 View 没有什么特别之处

@{
ViewBag.Title = "Employee Details";
}

<h2>Employee Details</h2>

<table style="font-family:Arial">
    <tr>
        <td>EmployeeID:</td>
        <td>@Model.EmployeeID</td>
    </tr>
    <tr>
        <td>Name:</td>
        <td>@Model.Name</td>
    </tr>
    <tr>
        <td>Gender:</td>
        <td>@Model.Gender</td>
    </tr>
    <tr>
        <td>City:</td>
        <td>@Model.City</td>
    </tr>
</table>

这是堆栈跟踪

at System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Single[TSource](IQueryable`1 source, Expression`1 predicate)
at MVCDemo.Controllers.EmployeeController.Details() in c:\Users\Admin\Documents\Visual Studio 2013\Projects\MVCDemo\MVCDemo\Controllers\EmployeeController.cs:line 19
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f<InvokeActionMethodFilterAsynchronously>b__49()

最佳答案

原因:当您使用 IIS 时,您的 App Pool 用户可能是“ApplicationPoolIdentity”。当连接到网络资源时,它将作为本地系统连接(所以如果在域中,那将是域\计算机$帐户)。据推测,该帐户无权访问 SQL 数据库。

某种修复:您对 IIS Express 的更改“修复”了此问题,连接是作为当前用户建立的。不过,如果您打算部署到 IIS,那就不好了。

更好的解决方法:将您的 IIS 应用程序池用户更改为真正的 Windows 用户帐户,该帐户可以访问 SQL DB。

我刚刚遇到了完全相同的问题,可以确认以上修复对我有效。

关于c# - 连接到数据库失败。检查连接字符串是否正确以及 DbContext 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22650556/

相关文章:

c# - 当用户按下 Enter/Return 键时调用服务器端操作

asp.net-mvc - 如何获取 ASP.NET MVC 区域的 web.config 中的值?

c# - DateTimeOffset.TryParseExact 的 AM/PM 有问题

c# - BackgroundWorker 报告来自外部类的进度?

sql - 我需要在 AdventureWorks (SQL 2005) 上进行慢速查询

c# - 为什么 SQL Server 实例不总是出现在枚举中?

sql-server - 您如何确保新索引不会减慢查询速度?

html - 表数据溢出容器

c# - 如何在没有多个 if 语句的情况下检查条件?

c# - VS/C# 调用方法时自动生成命名参数