使用实体框架6.1.1和模拟实现Async/Await

本文关键字:实现 Async Await 模拟 实体 框架 | 更新日期: 2023-09-27 18:17:48

我有一个托管在IIS中的WCF服务,它从多个来源(所有SQL Server)检索数据。对于每个数据源,我必须模拟不同的Active Directory用户才能连接到数据库。我使用实体框架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;
}

问题是前面的代码抛出了一个SqlException,表示运行web服务的帐户无法登录到数据库。似乎当我点击await时,我失去了模拟上下文。

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

使用实体框架6.1.1和模拟实现Async/Await

web.config中的legacyImpersonationPolicy设置为false, alwaysFlowImpersonationPolicy设置为true,并重新启动IIS

<configuration>
   <runtime>
     <legacyImpersonationPolicy enabled="false"/>
    <alwaysFlowImpersonationPolicy enabled="true"/>   
  </runtime>
</configuration>