ObjectContext.AddObject(String, Object) メソッド

定義

オブジェクトをオブジェクト コンテキストに追加します。

public:
 void AddObject(System::String ^ entitySetName, System::Object ^ entity);
public void AddObject (string entitySetName, object entity);
member this.AddObject : string * obj -> unit
Public Sub AddObject (entitySetName As String, entity As Object)

パラメーター

entitySetName
String

必要に応じてエンティティ コンテナー名で修飾できるエンティティ セット名を表します。

entity
Object

追加する Object

例外

entity パラメーターが null です。

- または -

entitySetName が修飾していません。

次の使用例は、新しい製品を追加し、変更をデータベースに保存します。

Product newProduct;

// Define values for the new product.
string dateTimeString = "1998-06-01 00:00:00.000";
string productName = "Flat Washer 10";
string productNumber = "FW-5600";
Int16 safetyStockLevel = 1000;
Int16 reorderPoint = 750;

// Convert the date time string into a DateTime instance.
DateTime sellStartDate;
if (!DateTime.TryParse(dateTimeString, out sellStartDate))
{
    throw new ArgumentException(string.Format("The string '{0}'cannot "
        + "be converted to DateTime.", dateTimeString));
}

// Create a new Product.
newProduct = Product.CreateProduct(0,
    productName, productNumber, false, false, safetyStockLevel, reorderPoint,
    0, 0, 0, DateTime.Today, Guid.NewGuid(), DateTime.Today);

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    try
    {
        // Add the new object to the context.
        context.Products.AddObject(newProduct);

        // Persist the new produc to the data source.
        context.SaveChanges();

        // Return the identity of the new product.
        return newProduct.ProductID;
    }
    catch (UpdateException ex)
    {
        throw new InvalidOperationException(string.Format(
            "The object could not be added. Make sure that a "
            + "product with a product number '{0}' does not aleady exist.\n",
            newProduct.ProductNumber), ex);
    }
}

注釈

オブジェクトをオブジェクト コンテキストに追加するには、AddObjectObjectContext を呼び出します。 この方法は、オブジェクトがデータ ソースに存在しない新しいオブジェクトである場合に使用します。 詳しくは、「オブジェクトのアタッチとデタッチ」をご覧ください。

オブジェクトは、ObjectStateManagerDetached、または Deleted 状態の Added に追加されます。

オブジェクト コンテキストで他のオブジェクトに関連する新しいオブジェクトを作成する場合、次のいずれかの方法でオブジェクトを追加します。

  • Add に対して EntityCollection<TEntity> メソッドを呼び出し、関連オブジェクトを指定します。 一対多または多対多のリレーションシップに対しては、この方法を使用します。

  • ValueEntityReference<TEntity> プロパティを関連オブジェクトに設定します。 一対一または多対一のリレーションシップに対しては、この方法を使用します。

詳細については、「 オブジェクトの作成、追加、変更、および削除」を参照してください。

オブジェクトがデタッチされた状態の場合は、 を EntityKey持つ必要はありません。

形式の entitySetName 規則は次のとおりです。

  • プロパティが のDefaultContainerNameentitySetName場合、 nullエンティティ コンテナー名>のように<完全修飾する必要があります。<エンティティ セット名>

  • が でないnull場合DefaultContainerNameは、 にentitySetNameエンティティ コンテナー名>のいずれかを<指定できます。<エンティティ セット名>または<エンティティ セット名>

objectEntityKeyentitySetName の値がある場合、エンティティ キーの はEntitySet、 および エンティティ コンテナー名にentitySetName基づいて検出された と一致EntitySetする必要があります。

適用対象

こちらもご覧ください