使用 Parallel.ForEach 插入和更新 CRM 数据

Using Parallel.ForEach for insert and update CRM data

我需要从外部更新 CRM 数据 table。一切正常,但速度很慢。这是我的代码:

static void Main(string[] args)
{
var dbClient = new CollectionEntities(); //Get database Entities
using(var xrm = new XrmServiceContext("Xrm"); // Get CRM Entities
    {
foreach (var row in dbClient.Client) //Reading rows from database
{
var c = (from a in crm.new_clientSet where a.new_Idnumber == row.Client_ID select a).FirstOrDefault(); // IS there clint with id from database
                            if (c == null)// if client not exist i create new if exists I update data
                            {
                                c = new new_client { new_Idnumber = row.Client_ID };
                                crm.AddObject(c);
                            }
                            c.new_name = row.Client_name; //[Client_name]
                            c.new_Idnumber = row.Client_ID;//[Client_ID]
                            c.EmailAddress = row.Email;//[Email]
                xrm.AddObject(c);
                    xrm.SaveChanges();

}
}
}

有了这个,我可以在 CRM 中插入和更新数据,但速度很慢。有没有办法使用这个 Parallel.ForEach 方法或其他一些方法来加速这个?谢谢!

您在每个循环中从 CRM 加载一行。这使您的应用非常 "chatty" 并且它在网络开销上花费的时间比加载数据要多。尝试在循环之前使用单个查询将整个 CRM 数据集加载到内存中。然后,在循环中,从内存中查找记录而不是查询 CRM。如果您的数据集很大,您可能需要使用分页 cookie。

查看开源 PFE Core Library for Dynamics CRM library from the Premier Field Engineering - Dynamics team at Microsoft. It handles parallelism for you. The Parallel Common Request 示例页面显示并行更新一堆记录是多么容易:

public void ParallelUpdate(List<Entity> targets)
{
    try
    {
        this.Manager.ParallelProxy.Update(targets);
    }
    catch (AggregateException ae)
    {
        // Handle exceptions
    }
}

您还可以使用它来查询大型数据集...它会为您检索所有内容。

在这种情况下,ExecuteMultipleRequest 绝对是正确的选择。

不同之处在于,您将发送单个请求,因此不会产生网络开销,而且,您的所有插入内容都将由 CRM 在服务器端处理,速度要快得多。