Share via


Creating, Adding, Modifying, and Deleting Objects

Objects in an object context are instances of entity types that represent data in the data source. You can modify, create, and delete objects in an object context, and the Entity Framework tracks the changes made to these objects. When the SaveChanges method is called, the Entity Framework generates and executes commands that perform the equivalent insert, update, or delete statements against the data source. For more information, see Saving Changes and Managing Concurrency

Mapping Insert, Update, and Delete Functions to Stored Procedures

The Entity Framework enables you to map the insert, update, and delete operations of an entity type to stored procedures. If you are planning to map stored procedures to your entities, it is recommended to map all three operations. If for example you map an entity type to insert and update stored procedures, but do not map to the delete stored procedure and then try to delete an object of that type, the delete operation will fail at runtime with UpdateException. For more information, see How to: Map Modification Functions to Stored Procedures and Walkthrough: Mapping an Entity to Stored Procedures.

Creating and Adding Objects

When you want to insert data in the data source, you must create an instance of an entity type and add the object to an object context. Before you can save a new object to the data source, you must first set all properties that do not support null values. When working with the Entity Framework generated classes, consider using the entity type's static CreateObjectName method to create a new instance of an entity type. The Entity Data Model tools include this method in each class when they generate the entity types. This create method is used to create an instance of an object and set all the properties of the class that cannot be null. The method includes a parameter for every property that has the Nullable="false" attribute applied in the CSDL file. For more information, see How to: Create an Object Using the Static Create Method.

When working with POCO ("plain-old" CLR objects) entities use the CreateObject method to create a new object instead of using the new operator. The CreateObject method wraps the new POCO instance in the appropriate proxy object. For more information, see Working with POCO Entities.

You can add new objects to an object context by using one of the following methods:

The following considerations apply when adding new objects:

  • Before SaveChanges is called, the Entity Framework generates a temporary key value for every new object. After SaveChanges is called, the key value is replaced by the identity value assigned by the data source when a new row is inserted.

  • If the key value of an entity is not generated by the data source, you should assign a unique value. If two objects have the same user-specified key value, an InvalidOperationException occurs when SaveChanges is called. If this occurs, you should assign unique values and retry the operation.

Adding Objects to a Specific EntitySet

There might be situations when an entity type belongs to multiple entity sets. For example, consider a situation where a database has two tables with identical schemas. This might be the case if you want to partition the data to produce a more efficient backup process. For example, you might have customer data partitioned between Customer and CustomerArchive tables, where CustomerArchive has the same schema as Customer but is used for customers who have not placed orders for more than six months. Customer might be backed up nightly, while CustomerArchive is only backed up weekly. From a mapping perspective, Customer and CustomerArchive must belong to different entity sets. The Entity Framework supports this scenario by letting an entity type exist in one or more entity sets. For more information, see EntitySet Element (CSDL).

When an entity type exists in multiple entity sets, the Entity Framework enables you to add new instances of the type to a specific entity set. Starting with the .NET Framework version 4, a generated ObjectContext class for a specific model has properties of type ObjectSet that represent the model’s entity sets. Use the AddObject method to add new objects to the object context. For more information, see Working with ObjectSet. In the .NET Framework version 3.5 SP1, you must specify the value of entitySetName when you call the AddObject method to add the object to the object context.

Modifying Objects

The Entity Framework tracks changes to objects that are attached to an ObjectContext. The Entity Data Model tools generate a pair of partial methods named OnPropertyChanging and OnPropertyChanged. These methods are called in the property setter. Extend these methods in partial classes to insert custom business logic during property changes. For more information, see How to: Execute Business Logic During Scalar Property Changes. For guidance on working with POCO entities, see Tracking Changes in POCO Entities.

The following considerations apply when modifying objects:

  • When any scalar or complex property of a complex object is changed, the state of the top-level entity object is changed to Modified. In the POCO entities that do not meet the requirements for the proxy generation, described in Requirements for Creating POCO Proxies, the state of the modified properties will be changed to Modified when the DetectChanges method is called.

  • Changes are not tracked when objects are in a Detached state. Objects are in this state when returned by a query that uses the NoTracking merge option or after being detached from an ObjectContext by calling Detach.

  • When you change a foreign key association, the state of the dependent object changes to Modified. When you change an independent association, the state of the dependent object does not change.

For information about tracking changes in POCO entities, see Tracking Changes in POCO Entities.

Deleting Objects

Calling the DeleteObject on the ObjectSet or DeleteObject method on ObjectContext marks the specified object for deletion. The row is not deleted from the data source until after SaveChanges is called.

When an entity object that is deleted has an association to other entities, the following considerations apply:

  • When working with a foreign key association, the Entity Framework sets nullable foreign key properties of dependent objects to null when the principal object is deleted.

  • When a primary key of the principal entity is part of the primary key of the dependent entity, then deleting the principal object also deletes all the loaded dependent objects. This is the same as defining the cascading delete rules on the relationship.

Cascade Delete Rules on Relationships

When you want to automatically delete all of the child records of a parent when the parent record is deleted you can specify the cascade delete rule. It is strongly recommended that you specify the cascade delete rules in both the conceptual model and the database. The reason the cascade delete rule has to be specified in both the database and the model is the Entity Framework only deletes the objects that are loaded in memory. For example, if you have loaded a parent with some but not all of the children, only children loaded in memory will be deleted when you delete the parent. This means, unless you have a corresponding cascade delete rule specified in the database, orphan records might be left in the database, or the delete might fail because of potential foreign key constraint violations.

When working with an independent association, the cascade delete operation may fail in one-to-one or one-to-zero or one relationship, unless you do one of the following:

  1. Load both ends of the one-to-one or one-to-zero or one relationship in the context. For more information, see the Loading Related Objects.

  2. Set the merge option to NoTracking when querying for objects where the other side of the relationship has multiplicity of one or zero-or-one and then attach the object to the context. In this case the database will perform the cascade delete.

For more information, see: Cascade Delete and 1-to1 (or 1-to-..1) Relationships.

Defining the Cascade Delete Rule

In the Entity Framework, the cascade rule is defined by the OnDelete element in the store schema definition language (SSDL) and the conceptual schema definition language (CSDL). For more information, see OnDelete Element (CSDL) and OnDelete Element (SSDL).

In a SQL Server database, you can set the cascade rule using SQL Server Management Studio. To set the rule, display the related tables in the Database Diagrams window. Select the relationship and press F4 to display the Properties window. In the Properties window, under the INSERT and UPDATE Specification property, set the Delete Rule to Cascade. When you generate a model from the database, the cascade rule will be imported into the model.

Bb738695.Tip(en-us,VS.100).gifTip:
If you update the database with the cascade delete rule and then update the existing model from the database, the Entity Framework will add the cascade delete rule to the SSDL but not CSDL. You will have to add it manually. To specify the cascade delete rule in the conceptual model, select the association on the Entity Designer surface. Then, in the Properties window, select Cascade for the OnDelete property.

In This Section

How to: Add, Modify, and Delete Objects

How to: Create an Object Using the Static Create Method

See Also

Tasks

How to: Define a Model with Multiple Entity Sets per Type
How to: Add, Modify, and Delete Objects

Concepts

Defining and Managing Relationships
Working with POCO Entities
Working with ObjectSet
Working with ObjectSet
OnDelete Element (CSDL)