当我能够设置值时,为什么我的Entity.Contains(属性字段)返回false?

时间:2015-02-23 00:47:37

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

我有一段代码无法按照我的想法运行。

我已经按照以下方式设置了一个实体并且有一个先前的guid。

parentEnt = new Entity("vehicle_ent");
parentEnt.id = guid;

现在我用声明做检查:

if (parentEnt.Contains("attribute_field")) {
    parentEnt["attribute_field"] = "test";
}

永远不会调用上面的内容,因为if语句失败了。

但是,如果我删除if语句。我能够实际分配和运行代码:

parentEnt["attribute_field"] = "test";

包含方法有什么我缺少的东西吗?我以为它用于检查实体是否包含属性?

3 个答案:

答案 0 :(得分:2)

在Entity类中,您始终可以分配一个属性,例如您提供的示例,无论它是否存在。如果它存在,它将覆盖它(这是你发现的)。

所以

parentEnt["attribute_field"] = "test";

无论属性是否已分配值,都将始终有效。

答案 1 :(得分:1)

运行CRM实体对象的构造函数时,为其指定一个guid 喜欢

Entity parentEnt = new Entity("vehicle_ent");
parentEnt.id = guid;

您正在创建一个实体类型的新对象,其中包含'vehicle_ent'逻辑名称和id为'guid'此时,属于具有该名称的实体的所有属性/属性都不会与实体对象,您只有一个设置了LogicalName和id的Entity类对象。

如果要检查具有该id的实体记录是否包含某个属性,则需要使用组织服务从数据库中获取,如

ColumnSet attributes = new ColumnSet(true);
parentEnt = _service.Retrieve("vehicle_ent", guid, attributes);

调用检索后,您可以检查实体记录是否包含您需要检查的属性。

答案 2 :(得分:1)

我只是添加了几件事:

语法entity[attributename]entity.Attributes[attributename]是等效的,原因可以在实体元数据中找到:

public object this[string attributeName] { get; set; } 

该方法在实体级别映射Attributes属性(此属性的类型为AttributeCollection,继承自DataCollection<string,object>,基类型为IEnumerable<KeyValuePair<TKey, TValue>>

DataCollection包含此方法:

    // Summary:
    //     Gets or sets the value associated with the specified key.
    //
    // Parameters:
    //   key:
    //     Type: TKey. The key of the value to get or set.
    //
    // Returns:
    //     Type: TValue The value associated with the specified key.
    public virtual TValue this[TKey key] { get; set; }

如果之前没有键,则此方法会在集合中添加键(我们的属性名称)。为此,您可以先为属性分配值,而不必使用Contains方法。当然,当您读取需要检查密钥是否存在的值时,这是Contains方法的目的,但是为了读取值GetAttributeValue也可以使用(但这是必要的)注意当属性不在集合中时返回的默认值)