SqlDependency with EntityFramework 6 (async)

后端 未结 1 1068
北海茫月
北海茫月 2020-12-29 11:29

I\'m using the EF 6 async querying features, such as

var list = await cx.Clients.Where(c => c.FirstName.Length > 0).ToListAsync();
         


        
相关标签:
1条回答
  • 2020-12-29 12:10

    I'm not too familiar with SqlDependency, but the below will allow your CallContext to have the correct value at the time ToListAsync is called (When multiple calls are running). Proof of concept here, https://dotnetfiddle.net/F8FnFe

        async Task<List<Client>> GetData()
        {
            using (ClientsContext context = new ClientsContext()) // subclass of DbContext
            {
                SqlDependency.Start(context.Database.Connection.ConnectionString);
                SqlDependency dependency = new SqlDependency();
                dependency.OnChange += (sender, e) =>
                {
                    Console.Write(e.ToString());
                };
    
                Task<List<Client>> task = Task<Task<List<Client>>>.Factory.StartNew(async () =>
                {
                    System.Runtime.Remoting.Messaging.CallContext.SetData("MS.SqlDependencyCookie", dependency.Id);
                    var list = await context.Clients.Where(c => c.FirstName.Length > 0).ToListAsync();
                }).Unwrap();
    
                return await task;
            }
        }
    
    0 讨论(0)
提交回复
热议问题