EntityCollection<TEntity>.Remove(TEntity) Método

Definição

Remove um objeto da coleção e marca a relação para exclusão.Removes an object from the collection and marks the relationship for deletion.

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

Parâmetros

entity
TEntity

O objeto a ser removido da coleção.The object to remove from the collection.

Retornos

Boolean

true se o item foi removido com êxito; caso contrário, false.true if item was successfully removed; otherwise, false.

Implementações

Exceções

O objeto entity é null.entity object is null.

O objeto entity não está anexado ao mesmo contexto de objeto.The entity object is not attached to the same object context.

- ou --or-

O objeto entity não tem um gerenciador de relação válido.The entity object does not have a valid relationship manager.

Exemplos

Este exemplo se baseia no modelo de vendas da Adventure Works.This example is based on the Adventure Works Sales Model. Para executar o código neste exemplo, você já deve ter adicionado o modelo de vendas AdventureWorks ao seu projeto e configurado seu projeto para usar o Entity Framework.To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. Para fazer isso, conclua os procedimentos em como configurar manualmente um projeto de Entity Framework e como definir manualmente o modelo e os arquivos de mapeamento.To do this, complete the procedures in How to: Manually Configure an Entity Framework Project and How to: Manually Define the Model and Mapping Files.

Este exemplo usa o Remove método para remover uma das entidades da coleção e, em seguida, chama o Contains método para determinar se o objeto foi removido da coleção.This example uses the Remove method to remove one of the entities from the collection and then calls the Contains method to determine whether the object was removed from the collection.

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);
    }
}
Using context As New AdventureWorksEntities()
    Dim contact As New Contact()

    ' Create a new SalesOrderHeader. 
    Dim newSalesOrder1 As New SalesOrderHeader()
    ' Add SalesOrderHeader to the Contact. 
    contact.SalesOrderHeaders.Add(newSalesOrder1)

    ' Create another SalesOrderHeader. 
    Dim newSalesOrder2 As New SalesOrderHeader()
    ' Add SalesOrderHeader to the Contact. 
    contact.SalesOrderHeaders.Add(newSalesOrder2)

    ' Get all related ends 
    Dim relEnds As IEnumerable(Of IRelatedEnd) = DirectCast(contact, IEntityWithRelationships).RelationshipManager.GetAllRelatedEnds()

    For Each relEnd As IRelatedEnd In relEnds
        ' Get Entity Collection from related end 
        Dim entityCollection As EntityCollection(Of SalesOrderHeader) = DirectCast(relEnd, EntityCollection(Of SalesOrderHeader))

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

        Dim contains As Boolean = 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 Then
            Console.WriteLine("The removed entity is not in in the collection any more.")
        End If

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

Comentários

O Remove método também exclui a relação entre o objeto de origem e o objeto que está sendo removido da coleção.The Remove method also deletes the relationship between the source object and the object being removed from the collection. Se a relação tiver uma restrição de integridade referencial, chamar o Remove método em um objeto dependente marcará a relação e o objeto dependente para exclusão.If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion. Isso ocorre porque a restrição indica que o objeto dependente não pode existir sem uma relação com o pai.This occurs because the constraint indicates that the dependent object cannot exist without a relationship to the parent. Para obter mais informações, consulte elemento ReferentialConstraint (CSDL).For more information, see ReferentialConstraint Element (CSDL).

Remove retorna false quando o objeto especificado não está na coleção.Remove returns false when the specified object is not in the collection.

Aplica-se a