动态CRM插件中Retieve与Update的关系

时间:2014-10-03 21:06:06

标签: dynamics-crm-2011 dynamics-crm-2013

Dynamic CRM插件中的Retrieve和Update之间是否存在关联? 例如,如果我只检索一个字段:

Entity e = (Entity)service.Retrieve("EntityLogicalName", EntityGuid, 
new ColumnSet(new string[] {"entityid"}));

我可以更新尚未检索到的实体e中的其他字段吗? 例如:

e.Attributes["AnotherEntityField1] = "test1";
e.Attributes["AnotherEntityField2] = "test2";
service.update(e);

如果不包括要在Retrieve中更新的所有字段,这可能会导致一些隐藏的问题吗?

3 个答案:

答案 0 :(得分:2)

假设您刚刚检索到实体的主键entityid,则您不需要进行检索。

Entity e = new Entity("EntityLogicalName") { Id = EntityGuid };
e.Attributes.Add("AnotherEntityField1", "test1");
e.Attributes.Add("AnotherEntityField2", "test2");
service.Update(e);

如果您正在进行检索以确认记录存在,则需要尝试/捕获或使用检索倍数,因为如果记录不存在,Retrieve将抛出异常。

答案 1 :(得分:1)

您要做的事情是完全可以接受的,不会造成任何问题。由于您通过Retrieve操作获取了Entity实例,因此将为更新正确设置所需的LogicalName和Id。

您的代码需要阅读如下内容,以便添加最初未检索到的新属性,否则您将获得KeyNotFoundException,因为Entity类型只是Dictionary<string,string>上的包装器。

e.Attributes.Add("AnotherEntityField2","test2");

答案 2 :(得分:0)

当您尝试更新实体时,您不需要在属性收集中存在字段,但要避免异常&#34;给定的密钥未在字典中显示&#34 ;最好先检查属性集合是否包含要更新的字段。如果是,则只需更新它,否则您必须将其添加到实体的属性集合中。

if(e.Attributes.Contains("AnotherEntityField1"))
{
e.Attributes["AnotherEntityField1"] = "test1";
}
else
{
e.Attributes.Add("AnotherEntityField1", "test1");
}

//现在更新操作