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

定義

コレクションにオブジェクトを追加します。

public:
 virtual void Add(TEntity entity);
public void Add(TEntity entity);
override this.Add : 'Entity -> unit
Public Sub Add (entity As TEntity)

パラメーター

entity
TEntity

コレクションに追加するオブジェクト。 entity IEntityWithRelationshipsを実装する必要があります。

実装

例外

entitynullです。

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

この例では、2 つの新しい SalesOrderHeader エンティティを作成し、 Contact エンティティに追加し、オブジェクトを削除した後、 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);
    }
}

注釈

Add メソッドは、EntityCollection<TEntity>にオブジェクトを追加し、2 つのオブジェクト間のリレーションシップを作成します。 ソース オブジェクトが ObjectContext インスタンスにアタッチされている場合、 Add メソッドはオブジェクトを ObjectContextにも追加します。 この操作は、 SaveChanges が呼び出されたときに、データ ソースの挿入操作に変換されます。 詳細については、「 オブジェクトの作成、追加、変更、および削除」を参照してください。

Add メソッドは、同じオブジェクト インスタンスで複数回呼び出すことができます。

適用対象