使用RIA服务对DomainContext进行批处理查询

本文关键字:批处理 查询 DomainContext RIA 服务 使用 | 更新日期: 2023-09-27 18:28:26

我有一个简单的Silverlight网页,它使用RIA服务显示来自远程数据库的dtaa。我有一个DomainContext,在其中我通过对数据库进行查询。

context.Load(context.GetSitesQuery()).Completed += new EventHandler(Query_Completed);

请注意,我正在等待查询完成。这里的问题是,我需要进行至少20个不同的查询,每个查询都涉及不同的实体对象。在加载所有数据之前,应用程序也不能做太多工作。所以,我真的只想知道所有查询何时完成。有没有一种简单的方法可以创建一批查询?

我自己尝试过,但由于每个查询都涉及不同的实体,所以遇到了问题。我创建了一个EntityQuery<Entity>的列表,并认为我可以对其进行迭代并执行所有查询,但Load方法要么抱怨参数错误,要么在运行时失败。

使用RIA服务对DomainContext进行批处理查询

我们已经通过跟踪挂起的加载操作的数量来完成您想要做的事情。当它达到0时,您实际上已经完成了。

using System.ServiceModel.DomainServices.Client;
...
private int _loadCounter;
private TheDomainContext _domainContext;
private void Load<TEntity>(EntityQuery<TEntity> query,
                           Action<LoadOperation<TEntity>> callback)
                       where TEntity : Entity
{
    BeginLoading();
    Action<LoadOperation<TEntity>> internalCallback = 
            loadOp => {
                          callback(loadOP);
                          EndLoading();
                      };
    _domainContext.Load(query, internalCallback , null);
}
private void BeginLoading()
{
    _loadCounter++;
    // You could add logic to indicate the app is busy
}
private void EndLoading()
{
    _loadCounter--;
    if (_loadCounter == 0)
    {
        OnLoadComplete();
    }
}
private void OnLoadComplete()
{
    // TODO Everything is loaded
}
private void BeginLoadingTheQueries()
{
    // Increment once here to prevent the OnLoadComplete from occurring
    // before all queries have started
    BeginLoading();
    Load(_domainContext.GetSitesQuery(), Query_Completed);
    Load(_domainContext.GetOtherQuery(), OtherQuery_Completed);
    EndLoading();
}