如何向查找字段添加值?

5

我在Microsoft Dynamics CRM中有一个名为“账户”的实体,其中有一些name_field。除了查找字段外,其他所有字段的值都可以插入。如何选择现有的lookup值?

我使用以下代码向lookup字段添加值。但是我没有收到任何错误提示。

Account acc = new Account();
acc.Attributes["name"] = "Ram"; // this values got inserted
acc.Attributes["age"] = "22"; // this values got inserted
acc.Attributes["lookupfieldid"] = "Sampletext";

service.Create(acc); // to create account

我需要如何更改我的代码才能选择查找字段中的“primary”值?

3个回答

10

在 CRM 2011 中,查找字段是通过 EntityReference 实现的,这意味着你需要知道该查找字段指向的实体的 LogicalName 和记录的 Id

因此,您的代码将如下所示:

Account acc = new Account();
acc.Attributes["name"] = "Ram"; // this values got inserted
acc.Attributes["age"] = "22"; // this values got inserted

acc.Attributes["lookupfieldid"] = new EntityReference("contact", contactId); // if lookupfieldid is pointing to contact entity

service.Create(acc); // to create account

一个考虑因素:你写道

Account acc = new Account();

我不知道您是否使用了早期绑定(也就是由crmsvcutil.exe生成的类),还是晚期绑定(在这种情况下,您将编写Entity acc = new Entity("account");

但如果您使用早期绑定,语法会类似于:

Account acc = new Account();
acc.Name = "Ram"; // this values got inserted
acc.Age = "22"; // this values got inserted
acc.LookupFieldId = new EntityReference("contact", contactId); // if lookupfieldid is pointing to contact entity
service.Create(acc); // to create account

使用早期绑定,您将在字段预期的正确类型之前知道。


谢谢回复, 我的要求是将默认值“Primary”插入到查找字段中。它有主要、次要和其他选项。我需要在创建帐户时插入主要值。如何将“Primary”值添加到我的查找字段中? - Ram K
我是新手。。我已经到处搜索了,但是找不到。:( 请帮帮我 - Ram K
请至少发布一张截图以了解您要更新的确切字段。 - Guido Preite
我的要求是从本地 SQL 数据库中读取内容,例如名称,年龄,帐户类型(查找字段)等,并将其导入到动态 CRM 2011 中。 - Ram K
如果我的数据库内容显示账户类型为“primary”,我想将相同的内容上传到CRM。如何选择查找字段中的值? - Ram K
显示剩余2条评论

4

根据您的描述,账户类型是一个实体(我们假设它被称为new_accounttype),具有一个名称字段(new_name)并且有三个实例分别命名为“Primary”、“Secondary”和“Other”。Lookupfieldid是一个外键,它链接到new_accounttype表。这意味着为了将账户类型查找设置为“Primary”,您需要知道new_name =“Primary”的账户类型实例的guid。

//Retrieve "Primary" account type
QueryExpression query = new QueryExpression("new_accounttype");
query.Criteria.AddCondition("new_name", ConditionOperator.Equal, "Primary");
Entity accountType = service.RetrieveMultiple(query).Entities.First();

//Set the lookup as Guido described above
Account acc = new Account();
acc.Attributes["name"] = "Ram";
acc.Attributes["age"] = "22";
acc.Attributes["lookupfieldid"] = new EntityReference("new_accounttype", accountType.Id);
service.Create(acc);

感谢您的回复。我尝试了您的代码,但出现了以下异常:系统.FormatException异常在尝试将输入值“Primary”转换为属性“new_accounttype.new_name”时抛出。属性值的预期类型为System.Guid。异常原因:Guid应包含32个带有4个破折号的数字(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)。 - Ram K
新名称是您的新账户类型实体上的字符串字段吗? - Zach Mast

0

获取查找字段的值

EntityReference entref = (EntityReference)item.Attributes[attributeName];

var LookupId = entref.Id;

var logicalName = entref.LogicalName;

设置查找字段的值

newAccount[attributeName] = new EntityReference(logicalName, LookupId);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接