ObjectContext.AddObject(String, Object) メソッド
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
オブジェクトコンテキストにオブジェクトを追加します。
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
エンティティ セット名を表します。この名前は、必要に応じてエンティティ コンテナー名で修飾できます。
例外
例
次の使用例は、新しい製品を追加し、変更をデータベースに保存します。
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);
}
}
注釈
オブジェクトコンテキストにオブジェクトを追加するには、ObjectContextに対してAddObjectを呼び出します。 この操作は、オブジェクトがデータ ソースにまだ存在しない新しいオブジェクトである場合に行います。
オブジェクトは、Detached、Deleted、またはAdded状態のObjectStateManagerに追加されます。
オブジェクト コンテキスト内の別のオブジェクトに関連する新しいオブジェクトを作成する場合は、次のいずれかのメソッドを使用してオブジェクトを追加します。
EntityCollection<TEntity>で Add メソッドを呼び出し、関連オブジェクトを指定します。 これは、一対多または多対多のリレーションシップに対して行います。
EntityReference<TEntity>のValueプロパティを関連オブジェクトに設定します。 これは、一対一または多対一のリレーションシップに対して行います。
オブジェクトがデタッチされた状態にある場合は、 EntityKeyを持つ必要はありません。
entitySetName形式の規則は次のとおりです。
DefaultContainerName プロパティが
nullされている場合、entitySetNameは <Entity Container Name>.< のように完全修飾する必要があります。エンティティ セット名>。DefaultContainerNameが
nullされていない場合、entitySetNameは <Entity コンテナー名>.<エンティティ セット名>または<エンティティ セット名>。
objectにEntityKeyがあり、entitySetNameに値がある場合、エンティティ キーのEntitySetは、entitySetNameとエンティティ コンテナー名に基づいて検出されたEntitySetと一致する必要があります。