title: How do you run EF 6 with Identity Impersonation? (Getting errors)
body: <p>So, we are trying to create a simple console app, but the console app needs to run it's connection to the SQL server with Windows Integrated mode.  Simple enough I say, I'll just impersonate a service account and connect to the SQL server that way.  Unfortunately, it comes down to not being able to find the EF assembly, even though, it's right next to the executable that is running.  If I take the same code and place it outside of my using statement for impersonation, the code works fine.  (I have rights to the SQL table, but our end users will not).</p>
  
  <p>The impersonation appears to be working, I can get the impersonated information and display it on the console, but nothing when it comes to dealing with EF 6.0.</p>
  
  <p>Anybody got any ideas?</p>
  
  <p>Thanks,
  Nick</p>
  
  <p>Updated with code:  Granted, this is proof of concept and relevant parts have been changed.</p>
  
  <pre><code>  private static void VILoggingInfo()
    {
       AppDomain myDomain = Thread.GetDomain();
       myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
       WindowsPrincipal myPrincipal = (WindowsPrincipal) Thread.CurrentPrincipal;
       // who am I right now?
       Console.WriteLine(myPrincipal.Identity.Name);
       string userName = "theUserName", domainName = "theDomain";
       const int LOGON32_PROVIDER_DEFAULT = 0;
       const int LOGON32_LOGON_INTERACTIVE = 2;
       SafeAccessTokenHandle safeAccessTokenHandle;
  
       bool returnValue = LogonUser(userName,
          domainName,
          "thePassword",
          LOGON32_LOGON_INTERACTIVE,
          LOGON32_PROVIDER_DEFAULT,
          out safeAccessTokenHandle);
  
       if (returnValue == false)
       {
          int ret = Marshal.GetLastWin32Error();
          Console.WriteLine("LogonUser failed with error code: {0}", ret);
          throw new System.ComponentModel.Win32Exception(ret);
       }
  
       WindowsIdentity.RunImpersonated(safeAccessTokenHandle,
          () =&gt;
          {
             using (var db = new VIDataModel())
             {
                var newRecord = new VIExecution
                {
                   LoginName = myPrincipal.Identity.Name,
                   ExecutionDate = DateTime.Now
                };
                db.VIExecutions.Add(newRecord);
                db.SaveChanges();
             }
  
          }
       );
    }
  </code></pre>