通过


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

注解

ObjectContext调用AddObject以将对象添加到对象上下文。 当对象是数据源中尚不存在的新对象时执行此操作。

对象将添加到处于ObjectStateManagerDetachedDeletedAdded状态。

在对象上下文中创建与另一个对象相关的新对象时,请使用下列方法之一添加对象:

如果对象处于分离状态,则它不得具有 EntityKey

格式的规则 entitySetName 如下所示:

  • DefaultContainerName如果该属性是null,则必须entitySetName实体容器名称<中>完全限定。<实体集名称>

  • 如果没有DefaultContainerNameentitySetName则可以是任一<实体容器名称>null<实体集名称><实体集名称>

object如果具有且EntityKeyentitySetName具有值,则EntitySet实体键必须与基于实体容器名称找到的entitySetName实体键匹配EntitySet

适用于

另请参阅