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



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

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 方法或其他方法来加速这一点? 谢谢!

在这种情况下,

ExecuteMultipleRequest 绝对是要走的路。

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

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

查看 Premier Field Engineering - Dynamics 团队的开源 PFE Core Library for Dynamics CRM 库 - Microsoft。 它为您处理并行性。 并行公共请求示例页面显示了并行更新一堆记录是多么容易:

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

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