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 销售模型。 若要运行此示例中的代码,必须将 AdventureWorks 销售模型添加到项目中,并将项目配置为使用 Entity Framework。 为此,请完成 如何:手动配置 Entity Framework Project如何:手动定义模型和映射文件

此示例使用 Remove 该方法从集合中删除其中一个实体,然后调用 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)。

Removefalse 指定的对象不在集合中时返回。

适用于