Я работаю над созданием системы торговых точек с использованием модели MVC на C# и SQL Server, но, похоже, у меня возникли проблемы с подключением к базе данных.
Web.config:
<?xml version = "1.0" encoding = "utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name = "entityFramework" type = "System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission = "false" />
</configSections>
<appSettings>
<add key = "webpages:Version" value = "3.0.0.0" />
<add key = "webpages:Enabled" value = "false" />
<add key = "ClientValidationEnabled" value = "true" />
<add key = "UnobtrusiveJavaScriptEnabled" value = "true" />
</appSettings>
<system.web>
<compilation debug = "true" targetFramework = "4.8" />
<httpRuntime targetFramework = "4.8" />
</system.web>
<system.webServer>
<handlers>
<remove name = "ExtensionlessUrlHandler-Integrated-4.0" />
<remove name = "OPTIONSVerbHandler" />
<remove name = "TRACEVerbHandler" />
<add name = "ExtensionlessUrlHandler-Integrated-4.0" path = "*." verb = "*" type = "System.Web.Handlers.TransferRequestHandler" preCondition = "integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns = "urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name = "Antlr3.Runtime" publicKeyToken = "eb42632606e9261f" />
<bindingRedirect oldVersion = "0.0.0.0-3.5.0.2" newVersion = "3.5.0.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name = "System.Web.Optimization" publicKeyToken = "31bf3856ad364e35" />
<bindingRedirect oldVersion = "0.0.0.0-1.1.0.0" newVersion = "1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name = "WebGrease" publicKeyToken = "31bf3856ad364e35" />
<bindingRedirect oldVersion = "0.0.0.0-1.6.5135.21930" newVersion = "1.6.5135.21930" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name = "Newtonsoft.Json" publicKeyToken = "30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion = "0.0.0.0-12.0.0.0" newVersion = "12.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name = "System.Web.Helpers" publicKeyToken = "31bf3856ad364e35" />
<bindingRedirect oldVersion = "0.0.0.0-3.0.0.0" newVersion = "3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name = "System.Web.Mvc" publicKeyToken = "31bf3856ad364e35" />
<bindingRedirect oldVersion = "0.0.0.0-5.2.7.0" newVersion = "5.2.7.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name = "System.Web.WebPages" publicKeyToken = "31bf3856ad364e35" />
<bindingRedirect oldVersion = "0.0.0.0-3.0.0.0" newVersion = "3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language = "c#;cs;csharp" extension = ".cs" type = "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel = "4" compilerOptions = "/langversion:default /nowarn:1659;1699;1701" />
<compiler language = "vb;vbs;visualbasic;vbscript" extension = ".vb" type = "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel = "4" compilerOptions = "/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<connectionStrings>
<add name = "mythellaneouspc.Cafeteria_POS"
connectionString = "metadata=res://*/Models.Cafeteria_POSModel.csdl|res://*/Models.Cafeteria_POSModel.ssdl|res://*/Models.Cafeteria_POSModel.msl;
provider=System.Data.SqlClient;
provider connection string="
Data Source= Cafeteria_POS;
Initial Catalog=Cafeteria_POS;
MultipleActiveResultSets=True;
App=EntityFramework""
providerName = "System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type = "System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value = "mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName = "System.Data.SqlClient" type = "System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Программа начинает работать и открывает окно браузера (IIS Express Google Chrome), но окно зависает при загрузке при попытке подключения к «https://localhost:44378/» и выдает эти 2 ошибки.
System.Data.Entity.Core.EntityException: 'The underlying provider failed on Open.'
SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
System.Data.Entity.Core.EntityException: 'The underlying provider failed on Open.'
Win32Exception: The network path was not found
Я пытался решить эту проблему в течение нескольких дней, но я не могу понять, что не так, и мне действительно нужна помощь в решении этой проблемы.
[РЕДАКТИРОВАТЬ #1]
После применения совета @ДэвидБраун-Майкрософт ошибки, которые у меня были, были исправлены, но теперь он выдает «System.Data.SqlClient.SqlException: Ошибка входа для пользователя». (SqlException (0x80131904)) в строке 26 файла ProfessorAdmin.cs, который я прикреплю ниже.
Вот фактический текст ошибки сервера:
Server Error in '/' Application.
Login failed for user ''.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Login failed for user ''.
Source Error:
Line 24: using (Cafeteria_POSEntities context = new Cafeteria_POSEntities())
Line 25: {
Line 26: return context.Faculties.Include(p => p.Plan).AsNoTracking().ToList();
Line 27: //AsNoTracking para no hacer copia en memoria porque no se hace ningun CRUD
Line 28: }
Source File: C:\Users\jpocu\source\repos\POS\POS\POS\Datos\FacultyAdmin.cs Line: 26
Stack Trace:
[SqlException (0x80131904): Login failed for user ''.]
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) +1524
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +467
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +70
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +940
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +111
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1567
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +118
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +268
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +315
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +128
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +265
System.Data.SqlClient.SqlConnection.Open() +133
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +98
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) +494
System.Data.Entity.SqlServer.<>c__DisplayClass2_0.<Execute>b__0() +18
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +234
System.Data.Entity.Core.EntityClient.EntityConnection.Open() +324
[EntityException: The underlying provider failed on Open.]
System.Data.Entity.Core.EntityClient.EntityConnection.Open() +741
System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection(Boolean shouldMonitorTransactions) +166
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +63
System.Data.Entity.Core.Objects.<>c__DisplayClass41_0.<GetResults>b__0() +227
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +234
System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +357
System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__31_0() +30
System.Data.Entity.Internal.LazyEnumerator`1.MoveNext() +39
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +453
System.Linq.Enumerable.ToList(IEnumerable`1 source) +73
POS.Datos.FacultyAdmin.Consultar() in C:\Users\jpocu\source\repos\POS\POS\POS\Datos\FacultyAdmin.cs:26
POS.Controllers.FacultyController.Index() in C:\Users\jpocu\source\repos\POS\POS\POS\Controllers\FacultyController.cs:19
lambda_method(Closure , ControllerBase , Object[] ) +87
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +35
System.Web.Mvc.Async.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +39
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +77
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0() +80
System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +396
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() +50
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +188
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +43
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +431
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +75
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +158
ФакультетАдмин.cs
using POS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
namespace POS.Datos
{
public class FacultyAdmin
{
public void Guardar(Faculty Employee)
{
using (Cafeteria_POSEntities context = new Cafeteria_POSEntities())
{
context.Faculties.Add(Employee);
context.SaveChanges();
}
}
public IEnumerable<Faculty> Consultar()
{
using (Cafeteria_POSEntities context = new Cafeteria_POSEntities())
{
return context.Faculties.Include(p => p.Plan).AsNoTracking().ToList();
//AsNoTracking para no hacer copia en memoria porque no se hace ningun CRUD
}
}
}
}
[РЕДАКТИРОВАТЬ #2]
Я добавляю это, чтобы изучить возможную ошибку в моей конфигурации строки подключения/SQL Server.
Диалоговое окно Microsoft SQL Server Management Studio «Подключиться к серверу»
@DavidBrowne-Microsoft О, хорошо, спасибо! Я переключил «Источник данных = Cafeteria_POS;» на "Источник данных = MYTHELLANEOUSPC ;" и эти исключения, похоже, исправлены, но теперь он выдает ту же ошибку с внутренним исключением «SqlException: Ошибка входа для пользователя». Основываясь на некоторых других статьях об этой ошибке, я попытался добавить «Integrated Security = false;», но, похоже, это не сработало, поскольку оно запускается и дает окно, в котором сообщается, что «Ошибка сервера в '/' Заявление." ([SqlException (0x80131904): Ошибка входа пользователя ''.]) Есть ли что-то еще, что я должен добавить, чтобы он работал?
Обычно это строка подключения
@Zee Я полагаю, что это как-то связано со строкой подключения, но не могли бы вы помочь/сказать мне, что именно мне нужно изменить/добавить в строку подключения, чтобы она заработала? Я был бы очень признателен!
@Mythellaneous Нужны ли вашей БД имя пользователя и пароль для подключения? или это просто локальная БД? Увидев ваше редактирование, вам, вероятно, понадобится имя пользователя и пароль.
@Zee Это просто локальная база данных, и я не настраивал для нее имя пользователя/пароль вручную. Есть ли конкретный параметр, который я могу найти в Microsoft SQL Server Management Studio, чтобы проверить, может ли он установить комбинацию имени пользователя и пароля по умолчанию или что-то в этом роде?
@Mythellaneous Попробуйте войти в систему с помощью SQL Studio. Проверьте имя сервера, если вы можете войти с именем сервера в строке подключения без имени пользователя и пароля, возможно, ваша строка подключения верна, иначе сообщите нам
@Zee Имя сервера — MYTHELLANEOUSPC, но я только что заметил, что он использует аутентификацию Windows. Может ли это быть проблема? (Я прикреплю скриншот этого выше.)
Опубликовал возможный ответ ниже, дайте мне знать, что это работает





Попробуйте добавить Trusted_Connection=True; в строку подключения.
<add name = "mythellaneouspc.Cafeteria_POS"
connectionString = "metadata=res://*/Models.Cafeteria_POSModel.csdl|res://*/Models.Cafeteria_POSModel.ssdl|res://*/Models.Cafeteria_POSModel.msl;
provider=System.Data.SqlClient;
provider connection string="
Data Source= Cafeteria_POS;
Initial Catalog=Cafeteria_POS;
Trusted_Connection=True;
MultipleActiveResultSets=True;
App=EntityFramework""
providerName = "System.Data.EntityClient" />
Оно работает! Большое спасибо за вашу помощь. ??
@Mythellaneous, пожалуйста, я был там :)
«При установлении соединения с SQL Server произошла ошибка, связанная с сетью или конкретным экземпляром. Сервер не найден или недоступен. Убедитесь, что имя экземпляра указано правильно и что SQL Server настроен на разрешение удаленных подключений». означает, что сервер с именем «Cafeteria_POS» не был найден или он не прослушивал порт по умолчанию 1433. Это обычное устранение неполадок с подключением SQL Server.