ObjectContext.AddObject(String, Object) Método

Definición

Agrega un objeto al contexto del objeto.Adds an object to the object context.

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)

Parámetros

entitySetName
String

Representa el nombre del conjunto de entidades, que puede estar calificado por el nombre del contenedor de entidades.Represents the entity set name, which may optionally be qualified by the entity container name.

entity
Object

El objeto Object que se va a agregar.The Object to add.

Excepciones

El parámetro entity es null.The entity parameter is null.

O bien-or-

entitySetName no se califica.The entitySetName does not qualify.

Ejemplos

Este ejemplo se basa en la Microsoft SQL Server Product Samples: Database.This example is based on the Microsoft SQL Server Product Samples: Database. En el ejemplo se agrega un nuevo producto y se guardan los cambios en la base de datos.The example adds a new product and saves the changes to the database.

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);
    }
}
Dim newProduct As Product

' Define values for the new product. 
Dim dateTimeString As String = "1998-06-01 00:00:00.000"
Dim productName As String = "Flat Washer 10"
Dim productNumber As String = "FW-5600"
Dim safetyStockLevel As Int16 = 1000
Dim reorderPoint As Int16 = 750

' Convert the date time string into a DateTime instance. 
Dim sellStartDate As DateTime
If Not DateTime.TryParse(dateTimeString, sellStartDate) Then
    Throw New ArgumentException(String.Format("The string '{0}'cannot be converted to DateTime.", dateTimeString))
End If

' Create a new Product. 
newProduct = Product.CreateProduct(0, productName, productNumber, False, False, safetyStockLevel, _
             reorderPoint, 0, 0, 0, DateTime.Today, Guid.NewGuid(), DateTime.Today)

Using context As 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 ex As UpdateException
        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.", _
                                                          newProduct.ProductNumber), ex)
    End Try
End Using

Comentarios

Llame a AddObject en el ObjectContext para agregar el objeto al contexto del objeto.Call AddObject on the ObjectContext to add the object to the object context. Haga esto cuando el objeto sea nuevo y no exista todavía en el origen de datos.Do this when the object is a new object that does not yet exist in the data source. Para obtener más información, vea adjuntar y separar objetos.For more information, see Attaching and Detaching Objects.

Los objetos se agregan al ObjectStateManager con el estado Detached, Deleted o Added.Objects are added to the ObjectStateManager in the Detached, Deleted or Added state.

Al crear un nuevo objeto relacionado con otro objeto del contexto del objeto, agregue el objeto con uno de los métodos siguientes:When you create a new object that is related to another object in the object context, add the object by using one of the following methods:

Para obtener más información, vea crear, agregar, modificar y eliminar objetos.For more information, see Creating, Adding, Modifying, and Deleting Objects.

Si el objeto está en un estado desasociado, no debe tener un EntityKey.If the object is in a detached state it must not have an EntityKey.

Las reglas para el formato de entitySetName son las siguientes:The rules for the entitySetName format are as follows:

  • Si la propiedad DefaultContainerName es null, el entitySetName debe ser completo como en <nombre del contenedor de entidades >. <> nombre del conjunto de entidades.If the DefaultContainerName property is null, then the entitySetName has to be fully qualified as in <Entity Container Name>.<Entity Set Name>.

  • Si DefaultContainerName no se null, el entitySetName puede ser <nombre de contenedor de entidades >. < nombre del conjunto de entidades > o <>.If DefaultContainerName is not null, then the entitySetName can be either <Entity Container Name>.<Entity Set Name> or <Entity Set Name>.

Si el object tiene un EntityKey y entitySetName tiene un valor, el EntitySet de la clave de entidad debe coincidir con el EntitySet que se encontró basándose en el entitySetName y el nombre del contenedor de entidades.If the object has an EntityKey and entitySetName has a value, then the EntitySet of the entity key must match the EntitySet that was found based on the entitySetName and entity container name.

Se aplica a

Consulte también: