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 一點要補充。

例外狀況

參數 entitynull

-或-

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加入 ,DeletedAdded 狀態。

當你建立一個與物件上下文中另一個物件相關的新物件時,請使用以下其中一種方法加入該物件:

若物體處於分離態,則不應該有 EntityKey

entitySetName 制規則如下:

  • 如果屬性DefaultContainerNamenull,則entitySetName必須完全符合實體容器名稱<中的>限定條件。<實體集合名稱>

  • DefaultContainerName不是null,則entitySetName可為實體容器名稱>。<<實體集合名稱><實體集合名稱>

如果 有 objectEntityKeyentitySetName 有值,那麼EntitySet實體鍵的 必須與根據 entitySetName 和 實體容器名稱所找到的 相符EntitySet

適用於

另請參閱