Calling EF Code First from Windows Service

c# ef-code-first entity-framework entity-framework-6 windows-services

Question

I'm trying to do a simple select system in the OnStart() event of a Windows service.But as soon as I introduce the code that talks to the database to the OnStart() event I get the following error:

An exception occurred while initializing the database. See the InnerException for details. The underlying provider failed on Open.

C# code:

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>

Stack trace:

  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
1
0
6/19/2015 11:38:42 AM

Accepted Answer

The problem was in my connection string.All I had to do was change the connection string to use SQL user name and password credentials, because the Windows Service that I created with Local System permissions didn't have access to talk to SQL

1
6/22/2015 7:12:04 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow