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

定義

コレクションからオブジェクトを削除し、リレーションシップを削除対象としてマークします。

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

パラメーター

entity
TEntity

コレクションから削除するオブジェクト。

返品

true 項目が正常に削除された場合。それ以外の場合は false

実装

例外

entity オブジェクトが null

entity オブジェクトが同じオブジェクト コンテキストにアタッチされていません。

-又は-

entity オブジェクトに有効なリレーションシップ マネージャーがありません。

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

この例では、 Remove メソッドを使用してコレクションからエンティティの 1 つを削除し、 Contains メソッドを呼び出して、オブジェクトがコレクションから削除されたかどうかを判断します。

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);
    }
}

注釈

Remove メソッドは、ソース オブジェクトとコレクションから削除されるオブジェクトの間のリレーションシップも削除します。 リレーションシップに参照整合性制約がある場合、依存オブジェクトに対して Remove メソッドを呼び出すと、リレーションシップと依存オブジェクトの両方が削除対象としてマークされます。 これは、この制約は、依存オブジェクトが親とのリレーションシップなしでは存在できないことを示しているために発生します。 詳細については、「 ReferentialConstraint 要素 (CSDL)」を参照してください。

Remove は、指定したオブジェクトがコレクション内にない場合に false を返します。

適用対象