我正在尝试在Windows服务的OnStart()
事件中执行一个简单的选择系统。但是,只要我将与数据库对话的代码引入OnStart()
事件,我就会得到以下错误:
初始化数据库时发生异常。有关详细信息,请参阅InnerException。底层提供程序在Open上失败。
C#代码:
protected override void OnStart(string[] args)
{
try
{
string serverName = GetServerName();
string serverIp = GetServerIP();
//This is the line that causes the exception
var dbContext = new DatabaseContext();
bool serverExists = dbContext.Server.Any(s => s.ServerName == serverName && s.ServerIp == serverIp);
if (!serverExists)
{
//Add server details to the DB
}
}
catch (Exception eX)
{
using (var w = new StreamWriter("C:\\ErrorFile.txt", true))
{
w.WriteLine(DateTime.Now.ToString("dd MM yyyy HH:mm:ss"));
w.WriteLine(eX.Message);
if (eX.InnerException != null)
w.WriteLine(eX.InnerException.Message);
w.WriteLine(eX.StackTrace);
w.WriteLine();
w.Close();
}
}
}
App.config中:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="ServiceManagerConnection" providerName="System.Data.SqlClient" connectionString="Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=ServiceManager;Data Source=." />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="ServiceRunInterval" value="5" />
</appSettings>
</configuration>
堆栈跟踪:
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
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.Any[TSource](IQueryable`1 source, Expression`1 predicate)
at mySuperSecretProjectName.Program.OnStart(String[] args) in c:\mySuperSecretProjectName\Program.cs:line 49
答案 0 :(得分:1)
问题出在我的连接字符串中。我所要做的就是更改连接字符串以使用SQL用户名和密码凭据,因为我使用本地系统权限创建的Windows服务无权访问SQL