ObjectContext::AddObject Method (String^, Object^)
Adds an object to the object context.
Assembly: System.Data.Entity (in System.Data.Entity.dll)
Parameters
- entitySetName
-
Type:
System::String^
Represents the entity set name, which may optionally be qualified by the entity container name.
- entity
-
Type:
System::Object^
The Object to add.
| Exception | Condition |
|---|---|
| ArgumentNullException | The entity parameter is null. -or- The entitySetName does not qualify. |
Call AddObject on the ObjectContext to add the object to the object context. Do this when the object is a new object that does not yet exist in the data source. For more information, see Attaching and Detaching Objects.
Objects are added to the ObjectStateManager in the Detached, Deleted or Added state.
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:
Call the Add method on the EntityCollection<TEntity> and specify the related object. Do this for a one-to-many or many-to-many relationship.
Set the Value property of the EntityReference<TEntity> to the related object. Do this for a one-to-one or many-to-one relationship.
For more information, see Creating, Adding, Modifying, and Deleting Objects.
If the object is in a detached state it must not have an EntityKey.
The rules for the entitySetName format are as follows:
If the DefaultContainerName property is null, then the entitySetName has to be fully qualified as in <Entity Container Name>.<Entity Set Name>.
If DefaultContainerName is not null, then the entitySetName can be either <Entity Container Name>.<Entity Set Name> or <Entity Set Name>.
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.
This example is based on the AdventureWorks Sales Model. The example adds a new product and saves the changes to the database.
Available since 3.5