我有以下方法从 Dynamics 中检索实体:
private Entity GetEntity(CrmOrganizationServiceContext context, string id, string entityLogicalName, params string[] columnSet)
{
Guid guid;
if (!Guid.TryParse(id, out guid))
{
return null;
}
if (columnSet != null && columnSet.Any())
{
return context.Retrieve(entityLogicalName, guid, new ColumnSet(columnSet));
}
return context.Retrieve(entityLogicalName, guid, new ColumnSet(allColumns: true));
}
我尝试检索 invoicedetail 实体并更新其属性。更新属性的方法如下所示:
public void UpdateAttributes(Entity entity, EntityDto entityDto)
{
foreach (var attribute in entityDto.Attributes)
{
entity[attribute.Key] = attribute.Value;
}
}
和更新方法:
public void Update(CrmOrganizationServiceContext context, IEnumerable<EntityDto> entities)
{
foreach (var entityDto in entities)
{
var entity = GetEntity(context, entityDto.CrmId.ExternalId, entityDto.TypeName, entityDto.Attributes.Keys.ToArray());
if (entity != null)
{
_entityService.UpdateAttributes(entity, entityDto);
context.Attach(entity);
context.UpdateObject(entity);
context.Update(entity);
}
context.SaveChanges();
}
}
我注意到对于发票实体,此方法有效,但是当我尝试检索发票详细信息(它是对发票实体的引用)并使用上述方法更新属性时,我不知从哪里获得了实体中的三个附加属性(全部其中是实体引用),当我尝试更新它时,出现异常:
System.ServiceModel.FaultException`1: 'System.InvalidCastException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #635D1534'
The invoicedetail entity attributes
Entity attributes that I want to update
正如我在 MSDN 上看到的那样,支持更新 invoicedetail 实体。如何解决此异常问题并更新 Dynamics 中的 invoicedetail 实体?
2017 年 6 月 21 日更新
经过几天的研究,我注意到如果我从发票详细信息实体的数据集中删除 priceperunit 属性,一切正常。我可以使用 priceperunit 在 Dynamics 中创建新实体,但我无法以相同的方式更新它。
entity["priceperunit"] = 999.0;
Dynamics 中此字段的类型是 Currency(如我所见,它不是实体引用),所以我猜想当我尝试更新此值时,Dynamics 将 decimal 转换为 Currency(或类似的东西)。有谁知道如何更新这种值(value)观?
最佳答案
你知道你的实体引用实际上是这一行中的 EntityReference
对象吗:
entity[attribute.Key] = attribute.Value;
也许它们是 Entity
或 EntityDto
对象,在这种情况下您将得到一个 InvalidCastException
。
如果您不确定并且无法调试,您可以键入检查它们并实例化一个 EntityReference
:
foreach (var attribute in entityDto.Attributes)
{
if (attribute.Value is Entity)
{
entity[attribute.Key] = new EntityReference(((Entity)attribute.Value).LogicalName, ((Entity)attribute.Value).Id);
}
// Check if EntityDto...
}
关于c# - 更新 Dynamics 发票详细信息实体时出现 InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44454654/