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);
}
}
備註
呼叫 AddObject , ObjectContext 將物件加入物件上下文。 當該物件是尚未存在於資料來源中的新物件時,請執行此操作。
物件會被ObjectStateManagerDetached加入 ,Deleted或 Added 狀態。
當你建立一個與物件上下文中另一個物件相關的新物件時,請使用以下其中一種方法加入該物件:
呼叫 Add 上 EntityCollection<TEntity> 的方法,並指定相關物件。 這對於一對多或多對多的關係都適用。
將 的EntityReference<TEntity>屬性設Value為相關物件。 請為一對一或多對一的關係做這件事。
若物體處於分離態,則不應該有 EntityKey。
賽 entitySetName 制規則如下:
如果屬性DefaultContainerName是
null,則entitySetName必須完全符合實體容器名稱<中的>限定條件。<實體集合名稱>。若DefaultContainerName不是
null,則entitySetName可為實體容器名稱>。<<實體集合名稱>或<實體集合名稱>。
如果 有 object 且 EntityKeyentitySetName 有值,那麼EntitySet實體鍵的 必須與根據 entitySetName 和 實體容器名稱所找到的 相符EntitySet。