2011-05-26 152 views
1

我注意到了CRM主持人大卫Jennaway在TechNet论坛指出,你不能使用LINQ更新/ 2011年CRM创建的记录在这里看到http://social.microsoft.com/Forums/en-IE/crmdevelopment/thread/682a7be2-1c07-497e-8f58-cea55c298062LINQ CRM 2011更新 - 创建

但我已经看到了一些线程,使它看起来好像它应该工作。这是我的尝试,不起作用。任何想法为什么不呢?

IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); 
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); 
OrganizationServiceContext orgContext = new OrganizationServiceContext(service); 

EntityState state = new EntityState(); 
state = EntityState.Changed; 

var counter = from c in orgContext.CreateQuery<pcx_entitycounter>() 
     where c.pcx_name.Contains("pcx_candidate") 
     select new pcx_entitycounter 
     {Id = c.Id, 
     pcx_name = c.pcx_name, pcx_Sequence = c.pcx_Sequence, pcx_Prefix = c.pcx_Prefix 

     }; 

foreach (var c in counter) 
     { 
      string prefix = c.pcx_Prefix.ToString(); ; 
      string sequence = c.pcx_Sequence.ToString(); 

      c.pcx_Sequence = c.pcx_Sequence + 1; 
      c.EntityState = state; 
      **service.Update(c);** //FAILS HERE 

     } 
+2

此LINQ如何进行更新?我看到你正在运行一个LINQ查询,但没有在实际的更新?你有什么异常? – 2011-05-26 21:09:02

+0

当然会有助于查看例外情况以及所有相关细节。 – cchamberlain 2011-06-05 16:15:58

回答

2

以我的经验来说,这是难以不可能从上下文检索实体,更新它,然后用该服务保存更改。它让我头疼!

由于您的检索代码使用来自上下文的查询,所有这些实体都应该附加到上下文,并且它们的状态正在被跟踪。因此,你需要使用上下文的方法来更新:

foreach (var c in counter) { 
    string prefix = c.pcx_Prefix.ToString(); ; 
    string sequence = c.pcx_Sequence.ToString(); 

    c.pcx_Sequence = c.pcx_Sequence + 1; 

    // Use the Context to save changes 
    orgContext.UpdateObject(c); 
    orgContext.SaveChanges(); 
} 

因为很多我的代码将检索根据情况不同的方式(即服务或上下文)的实体,我已经开发了知道如何的简单方法正确更新实体。要扩大你的榜样,你可能会有类似的更新方法:

public void UpdatePcxEntityCounter(pcx_entitycounter c) { 
    if (!orgContext.IsAttached(c)) { 
     service.Update(c); 
    } 
    else { 
     orgContext.UpdateObject(c); 
     orgContext.SaveChanges(); 
    } 
} 

这假定两者orgContextservice可在上面说的方法的范围。否则,他们必须作为附加参数传递。

0

在没有看到困难的难以辨别的问题是什么,但你尝试过使用orgContext.UpdateObject(C);在执行更新步骤之前?此外,不知道为什么你要分配的前缀和序列本地变量在你的循环,因为他们似乎没有被使用。它有可能会得到一个SOAP异常或者分配值不起作用的值。你有没有在实体上注册任何插件?

请参见下面的链接,可能的解决方案 -

How to update a CRM 2011 Entity using LINQ in a Plugin?

http://social.microsoft.com/Forums/en-US/crmdevelopment/thread/7ae89b3b-6eca-4876-9513-042739fa432a