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>内で検索するオブジェクト。

返品

true オブジェクトが EntityCollection<TEntity>で見つかった場合は a0/>。それ以外の場合は false

実装

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

この例では、次のことが行われます。

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

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

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

  4. 関連する各エンドの 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)
            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 メソッドを使用して、指定したオブジェクトとコレクション内のオブジェクトを比較します。

適用対象