Async/Await with Entity Framework 6.1.1和模拟

Ala*_*n P 8 .net c# sql-server entity-framework async-await

我有一个托管在IIS中的WCF服务,它从多个源(所有SQL Server)检索数据.对于每个数据源,我必须模拟不同的Active Directory用户才能连接到数据库.我正在使用Entity Framework v6.1.1来处理两个数据源.集成安全性也在连接字符串中设置为True.

我使用下面的示例来设置模拟用户,其中模拟用户是System.Security.Principal.WindowsImpersonationContext我从配置中设置的用户:

internal async Task<List<string>> GetItemsByLookupItemsAsync(List<string> lookupItems) 
{
    var result = new List<string>();

    using (var db = new EntityFrameworkDb()) 
    {

        var query = from item in db.Table
                    where lookupItems.Contains(item.LookupColumn)
                    select item.StringColumn;

        var queryResult = new List<string>();
        using (GetImpersonatedUser())
        {
            queryResult.AddRange(await query.ToListAsync());
        }

        result.AddRange(queryResult.OrderBy(e => e));
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

问题是前面的代码抛出了一个SqlException说法,即运行Web服务的帐户无法登录到数据库.看来,当我击中时,await我失去了模仿背景.

有什么建议可以解决这个问题?

Yuv*_*kov 7

legacyImpersonationPolicyfalsealwaysFlowImpersonationPolicytrue你的内部web.config,并重新启动IIS

<configuration>
   <runtime>
     <legacyImpersonationPolicy enabled="false"/>
    <alwaysFlowImpersonationPolicy enabled="true"/>   
  </runtime>
</configuration>
Run Code Online (Sandbox Code Playgroud)