我有一个实体,它有一个或多个Money
- 字段。因此,它还有一个transactioncurrencyid
字段,用于指定记录的货币。
现在,当我在浏览器中创建该实体的记录时,transactioncurrencyid
- 字段会预先填充系统或用户的默认货币。
但是,在通过SDK创建该实体的记录而未指定任何Money
- 字段的值时,transactioncurrencyid
字段保持为空。之后,没有用户能够编辑任何Money
字段,因为未设置货币:
如果货币字段中存在值,则需要货币。选择一个 货币,然后再试一次。
奇怪的是,当我为Money-field设置一个值时(即使我不告诉它使用什么货币),这不会发生,例如:
var entity = new Entity("new_myentity")
{
Attributes =
{
{ "name" = "Name 1" },
{ "amount" = new Money(1000) }
}
}
所以我的问题是:
有没有办法在通过SDK创建记录时将其设置为默认值而没有任何已填充的Money
- 属性?
答案 0 :(得分:2)
这个问题一旦出现,起初很困惑,因为它似乎没有模式,但是接着是,手动创建的记录没问题,但是由Web门户创建的记录会将transactioncurrencyid设置为null(只有在创建中没有指定货币字段时。
所以我将以下代码添加到post-create插件中,确保始终填充此字段。在这个例子中,我特意使用欧元货币,但是可以修改检索货币guid的方法以返回默认值。
IOrganizationService service = localContext.OrganizationService;
Entity retrievedEntity = localContext.PluginExecutionContext.InputParameters["Target"] as Entity;
if (retrievedEntity.LogicalName == Account.EntityLogicalName)
{
try
{
Entity updatedEntity = new Entity(retrievedEntity.LogicalName);
updatedEntity.Id = retrievedEntity.Id;
//Autopopulate the Transaction Currency field - only if transactioncurrencyid field is missing in Attributes collection
if (!retrievedEntity.Attributes.Contains("transactioncurrencyid"))
{
string euroCurrencyId = RetrieveEuroCurrencyId(service);
if (euroCurrencyId != null)
{
EntityReference currencyType = new EntityReference();
currencyType.Id = new Guid(euroCurrencyId);
currencyType.LogicalName = TransactionCurrency.EntityLogicalName;
updatedEntity.Attributes.Add(new KeyValuePair<string, object>("transactioncurrencyid", currencyType));
updatedEntity.Attributes["transactioncurrencyid"] = currencyType;
}
}
localContext.OrganizationService.Update(updatedEntity);
}
catch (Exception ex)
{
throw;
}
}
检索货币guid的方法如下所示......
//Use this method to return the Guid for the Euro currency
public static String RetrieveEuroCurrencyId(IOrganizationService service)
{
String result = null;
QueryExpression query = new QueryExpression();
query.EntityName = TransactionCurrency.EntityLogicalName;
query.ColumnSet = new ColumnSet(new string[] { "transactioncurrencyid", "currencyname" });
query.Criteria = new FilterExpression();
EntityCollection currencies = service.RetrieveMultiple(query);
foreach (Entity e in currencies.Entities)
{
if (e.Attributes.Contains("currencyname"))
{
if (e.Attributes["currencyname"].ToString() == "Euro")
result = e.Attributes["transactioncurrencyid"].ToString();
}
}
return result;
}