简体   繁体   English

Dynamics CRM:CreateRequest并发问题

[英]Dynamics CRM: CreateRequest concurrency issue

I am using MS Dynamics CRM SDK with C#. 我正在使用带有C#的MS Dynamics CRM SDK。 In this I have a WCF service method which creates an entity record. 在这里,我有一个WCF服务方法,它创建一个实体记录。 I am using CreateRequest in the method. 我在方法中使用CreateRequest Client is calling this method with 2 identical requests one after other immediately. 客户端立即使用两个相同的请求调用此方法。

There is a fetch before creating a record. 创建记录之前需要进行提取。 If the record is available we are updating it. 如果记录可用,我们将对其进行更新。 However, 2 inserts are happening at the exact time. 但是,在正确的时间发生了2次插入。 So 2 records with identical data are getting created in CRM. 因此,将在CRM中创建具有相同数据的2条记录。

Can someone help to prevent concurrency? 有人可以帮助防止并发吗?

You should force the duplicate detection rule & decide what to do. 您应强制执行重复检测规则并决定要执行的操作。 Read more 阅读更多

Account a = new Account();
a.Name = "My account";

CreateRequest req = new CreateRequest();
req.Parameters.Add("SuppressDuplicateDetection", false);
req.Target = a;
try
{
    service.Execute(req);
}
catch (FaultException<OrganizationServiceFault> ex)
{
    if (ex.Detail.ErrorCode == -2147220685)
    {
        // Account with name "My account" already exists
    }
    else
    {
        throw;
    }
}

As Filburt commented in your question, the preferred approach would be to use an Alternate Key and Upsert requests but unfortunately that's not an option for you if you're working with CRM 2013. 正如Filburt在您的问题中评论的那样,首选方法是使用备用键Upsert请求,但不幸的是,如果您使用CRM 2013,这不是您的选择。

In your scenario, I'd implement a very lightweight cache in the WCF service, probably using the MemoryCache object from the System.Runtime.Caching.dll library ( small example ). 在您的方案中,我可能在WCF服务中实现了非常轻量级的缓存,可能使用了System.Runtime.Caching.dll库中的MemoryCache对象( 小示例 )。 Before executing the query to CRM, you can check if the record exists in the cache and continue with you current processing if it doesn't (remembering to add the record to the cache with a small expiration time for potential concurrent executions) or handle the scenario where the record already exists in the cache (and here you can go from having quite complex checks to detect and prevent potential data loss/unnecessary updates to a simple and stupid Thread.Sleep(1000) ). 在执行对CRM的查询之前,您可以检查记录是否存在于缓存中,如果不存在,则继续进行当前处理(记住将记录添加到缓存中的有效期限短,以进行潜在的并发执行)或处理该记录。记录已经存在于高速缓存中的场景(在这里,您可以进行相当复杂的检查以检测并防止潜在的数据丢失/不必要的更新,变成简单而愚蠢的Thread.Sleep(1000) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM