Windows 使用 TopShelf 的服务:基础提供程序打开失败。用户登录失败

Windows service using TopShelf: The underlying provider failed on Open. User logon failure

我的项目是由 TopShelf 创建的 window 服务。它在本地数据库中存储数据但发生错误:

System.Data.Entity.Core.EntityException: The underlying provider failed on Open. > System.Data.SqlClient.SqlException: User logon failure 'USER'

我的字符串连接是:

  <connectionStrings>
    <add name="ValeQpsContext" connectionString="Data Source=.\SQLEXPRESS01;Initial Catalog=Vale.Qps;Integrated Security=False;
         User Id=USER; Password=xxxx" 
         providerName="System.Data.SqlClient" />
  </connectionStrings>

我的数据库是使用 SQL EXPRESS 的本地数据库,我的服务 运行 作为本地系统。

这是在数据库中存储数据的方法:

public static void Insert<T>(T entity)
            where T : class
        {
            try
            {
                using (var ctx = new MyContext())
                {
                    ctx.Entry(entity).State = System.Data.Entity.EntityState.Added;

                    ctx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

这是一个完整的内部异常:

The underlying provider failed on Open. System.Data.Entity.Core.EntityException: The underlying provider failed on Open. > System.Data.SqlClient.SqlException: User logon failure 'USER'. em System.Data.ProviderBase.DbConnectionPool.TryGetConnection em System.Data.ProviderBase.DbConnectionPool.TryGetConnection em System.Data.ProviderBase.DbConnectionFactory.TryGetConnection em System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal em System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection em System.Data.SqlClient.SqlConnection.TryOpenInner em System.Data.SqlClient.SqlConnection.TryOpen em System.Data.SqlClient.SqlConnection.Open em System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<>c.b__13_0 em System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch em System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open em System.Data.Entity.Core.EntityClient.EntityConnection.b__55_0 em System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass2_0.b__0 em System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute em System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute em System.Data.Entity.Core.EntityClient.EntityConnection.Open

相同的权限(用户和密码)在 SSMS 中定义到数据库。错误在哪里?

我找到了解决方案。我将连接字符串更改为:

  <connectionStrings><add name="MyContext" connectionString="Data Source=.\SQLEXPRESS01;Initial Catalog=MyDatabase;Integrated Security=SSPI;AttachDBFilename=C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS01\MSSQL\DATA\MyDatabase.mdf;User Id=DOMAIN\USER; Password=xxxxx" providerName="System.Data.SqlClient" /></connectionStrings>

而且我还更改了安装服务的命令。添加登录用户:

MyService.exe install -username:DOMAIN\USER -password:xxxx start

所以,这不是完全错误,但现在没问题了。