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);
    }
}

備註

您可以在 AddObject 上呼叫 ObjectContext,以便將此物件加入至物件內容。 請於此物件為新物件 (還不在資料來源中) 時執行此動作。 如需詳細資訊,請參閱連結和中斷連結物件

物件會加入至處於 ObjectStateManagerDetachedDeleted 狀態中的 Added

當您建立與物件內容中另一個物件相關的新物件時,請使用下列其中一種方法來加入此物件:

  • 針對 Add 呼叫 EntityCollection<TEntity> 方法並指定相關物件。 請針對一對多關聯性 (One-To-Many Relationship) 或多對多關聯性 (Many-To-Many Relationship) 進行此步驟。

  • ValueEntityReference<TEntity> 屬性設定為相關物件。 請針對一對一關聯性 (One-To-One Relationship) 或多對一關聯性 (Many-To-One Relationship) 進行此步驟。

如需詳細資訊,請參閱 建立、新增、修改和刪除物件

如果物件處於中斷連結狀態,則它不能有 EntityKey

格式的規則 entitySetName 如下所示:

  • DefaultContainerName如果 屬性為 null,則必須entitySetName實體容器名稱<><中完整。實體集名稱>

  • 如果 DefaultContainerName 不是 null,則 entitySetName 可以是實體<容器名稱><實體集名稱><實體集名稱>

object如果具有且 entitySetName 具有 EntityKey 值,則EntitySet實體索引鍵的 必須符合EntitySet根據 和實體容器名稱找到的 entitySetName

適用於

另請參閱