EntityCollection<TEntity>.Contains(TEntity) メソッド

定義

特定のオブジェクトがコレクション内に存在するかどうかを確認します。

public:
 virtual bool Contains(TEntity entity);
public bool Contains (TEntity entity);
abstract member Contains : 'Entity -> bool
override this.Contains : 'Entity -> bool
Public Function Contains (entity As TEntity) As Boolean

パラメーター

entity
TEntity

EntityCollection<TEntity> 内で検索するオブジェクト。

戻り値

そのオブジェクトが EntityCollection<TEntity> に存在する場合は true。それ以外の場合は false

実装

この例には、Adventure Works Sales Model が使用されています。 この例のコードを実行するには、あらかじめプロジェクトに AdventureWorks Sales Model を追加し、Entity Framework を使用するようにプロジェクトを構成しておく必要があります。 これを行うには、「 方法: Entity Framework プロジェクトを手動で構成する 」および 「方法: モデル ファイルとマッピング ファイルを手動で定義する」の手順を完了します。

この例の内容は次のとおりです。

  1. 2 つの新しい SalesOrderHeader エンティティを作成して Contact エンティティに追加します。

  2. Contact エンティティに関連付けられている RelationshipManager からすべての関連 End を取得します。

  3. IRelatedEnd のコレクションを反復処理します。

  4. 各関連 End の EntityCollection<TEntity> を取得します。

  5. Remove メソッドを使用して、コレクションからエンティティを 1 つ削除します。

  6. Contains メソッドを呼び出して、そのオブジェクトがコレクションから削除されたかどうかを確認します。

  7. Add メソッドを使用して、削除したエンティティを再び追加します。

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    Contact contact = new Contact();

    // Create a new SalesOrderHeader.
    SalesOrderHeader newSalesOrder1 = new SalesOrderHeader();
    // Add SalesOrderHeader to the Contact.
    contact.SalesOrderHeaders.Add(newSalesOrder1);

    // Create another SalesOrderHeader.
    SalesOrderHeader newSalesOrder2 = new SalesOrderHeader();
    // Add SalesOrderHeader to the Contact.
    contact.SalesOrderHeaders.Add(newSalesOrder2);

    // Get all related ends
    IEnumerable<IRelatedEnd> relEnds =
        ((IEntityWithRelationships)contact)
        .RelationshipManager.GetAllRelatedEnds();

    foreach (IRelatedEnd relEnd in relEnds)
    {
        // Get Entity Collection from related end
        EntityCollection<SalesOrderHeader> entityCollection =
            (EntityCollection<SalesOrderHeader>)relEnd;

        Console.WriteLine("EntityCollection count: {0}",
            entityCollection.Count);
        // Remove the first entity object.
        entityCollection.Remove(newSalesOrder1);

        bool contains = entityCollection.Contains(newSalesOrder1);

        // Write the number of items after one entity has been removed
        Console.WriteLine("EntityCollection count after one entity has been removed: {0}",
            entityCollection.Count);

        if (contains == false)
            Console.WriteLine("The removed entity is not in in the collection any more.");

        //Use IRelatedEnd to add the entity back.
        relEnd.Add(newSalesOrder1);
        Console.WriteLine("EntityCollection count after an entity has been added again: {0}",
            entityCollection.Count);
    }
}

注釈

指定したオブジェクトをコレクション内の既存のオブジェクトと比較するには Object.Equals メソッドを使用します。

適用対象