连接数据库失败.检查连接字符串是否正确和DbContext构造函数

本文关键字:连接 DbContext 构造函数 是否 数据库 失败 检查 字符串 | 更新日期: 2023-09-27 17:53:14

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

我发誓我什么都试过了!通过本教程,并努力获得连接到数据库。

我在SQL Server 2012中的表名为"tbleemployee",数据库名为"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; }
}

这是employeecontroller

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

这是网页。配置文件

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

实际视图没有什么特别的

@{
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()

连接数据库失败.检查连接字符串是否正确和DbContext构造函数

原因:当您使用IIS时,您的应用程序池用户可能是'ApplicationPoolIdentity'。当连接到网络资源时,它将作为本地系统连接(因此,如果在域中,它将是域'计算机$帐户)。假定该帐户没有访问SQL DB的权限。

Sort fix:您对IIS Express的更改"修复"了这个,连接是作为当前用户进行的。但如果你打算部署到IIS,那就不太好了。

更好的修复:将你的IIS应用池用户更改为一个真正的Windows用户帐户,该帐户可以访问SQL数据库。

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

我的主要项目,其中包含web。配置文件(包含连接字符串)未设置为默认项目。将其设置为默认项目解决了这个问题。

我有类似的错误和修复。当我在解决方案中设置包含我的ApplicationDbContext类的"启动项目"时,我有两个以上的模块。右键单击模块>>点击"设置为启动项目"

在经历了相当多的挣扎之后,这就是我的工作:

-1)卸载SQL Server

-2)重新安装SQL Server并设置一个新的实例(INST01)

^^我不认为上面的任何一个实际上有任何作用。

-3)通过转到SQL server对象资源管理器并定位新实例,使用Visual Studio重新连接到新服务器。

-4)回到SQL Server管理工作室,重新创建了我的简单数据库。

-5)在SQL Server对象资源管理器下,我从数据库属性复制了连接字符串。

-6)我将项目的Web属性从本地IIS更改为IIS Express。

-7)卸载EntityFramework 6

-8)删除了web中对实体框架的任何引用。配置文件(这样EF 5的代码将在安装时插入)

-9)从包管理器控制台安装EntityFramework 5.0.0 .

-10)运行应用程序,它工作了。

我不能100%确定问题是什么,但我认为它与本地IIS和IIS Express有关。我认为更改EF框架版本是必要的,以确保调用表的语法是一致的。

请记住,在所有这些之前,我可以通过简单地进入SQL Server对象资源管理器建立到数据库的连接。我甚至可以在Visual Studio中打开表格,查看Data.

希望这对某人有帮助:)

如果你的服务器是2012 sql express免费版,那么你的连接字符串应该是这样的。

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

数据源应该是=Admin-PC'SQLEXPRESS…

也看看这个SQL 2012连接字符串

更新

参考DbConfiguration类,

从该类派生的类可以放置在与一个从DbContext派生的类来定义实体框架应用程序的配置。通过调用来设置配置中设置该类的受保护属性派生类型的构造函数。使用的类型也可以是在应用程序的配置文件中注册。

DbConfiguration的派生类应该和DbContext在同一个程序集中。

在我的ADO案例中。. NET实体数据模型,我发现我的类派生自DbContext在Model1。edmx -> Model1.Context.cs -> Model1.Context.cs

代码应该配置你的清单令牌,并希望它能解决你的问题。


我在这里发现了类似的问题,希望能帮助你解决你的问题。

参考moozzyk,

好消息是,要解决这个问题,您实际上不必更改EF代码。

EF6允许配置服务,其中一个服务允许重写获取提供商清单令牌的默认行为。

您可以使用基于代码的配置注册您的自定义清单令牌解析器,并返回硬编码值(例如,如果您总是针对SqlServer 2012运行,则只需返回"2012")或自己提出版本。

这应该防止EF检查数据库版本你的应用程序正在运行。

如果你运行不同版本的Sql Server,你可以使用DbConnection。ServerVersion属性为数据库创建一个提供者清单令牌

这里有一个例子-你可以复制/粘贴,它应该工作,因为EF应该检测配置 *自动*(只要DbConfiguration派生类与上下文在同一个程序集中)

public class Configuration : DbConfiguration
{
    public Configuration()
    {
        SetManifestTokenResolver(new ManifestTokenResolver());
    }
}
public class ManifestTokenResolver : IManifestTokenResolver
{
    public string ResolveManifestToken(DbConnection connection)
    {
        // The simplest thing is just to return hardcoded value
        // return "2012";
        try
        {
            connection.Open();
            var majorVersion =
                Int32.Parse(connection.ServerVersion.Substring(0, 2), CultureInfo.InvariantCulture);
            if (majorVersion == 9)
            {
                return "2005";
            }
            if (majorVersion == 10)
            {
               return "2008";
            }
            return "2012";
        }
        finally 
        {
            if (connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }
    }
}

我在IIS上托管MVC应用程序时也面临同样的问题。错误:无法打开登录请求的数据库"MVCDemo"。登录失败。用户"IIS appool 'ASP"登录失败。净v4.0。"

临时修复本地用户不用于部署:代替部署在IIS上,我们可以使用IISExpress,转到项目->属性->Web->启用单选按钮,使用本地IIS服务器并勾选设置使用IISExpress。

系统规格:VS 2012,