The examples contained in this article all refer to the EDM called EDMExample.
Inserting new data is just adding new objects to the context collections. When the changes are ready to send to the database, call the SaveChanges method of the context. Before doing this, all properties that do not support null (Nothing) values must be set. The SaveChanges method calls in to the entity provider to generate and execute commands that perform the equivalent INSERT, UPDATE, or DELETE statements against the database.
Here is code to add a new customer to the database.
EDMExample |
Copy Code
|
---|---|
EDMExample context = new EDMExample (); // Create a new product Customer newCustomer = new Customer(); newCustomer.CustomerID = 1; newCustomer.CompanyName = "New customer 1"; context.AddToCustomers(newCustomer); // Send the changes to the database. // Until SaveChanges() is called, the changes are cached on the client side. context.SaveChanges(); |
The methods AddToCustomer and others are automatically generated in the context. Similar methods exist for every class in your model.
Entity instances are modified as usual. The only thing to remember is to invoke the SaveChanges method to send the data to the database.
UpdateExample |
Copy Code
|
---|---|
newCustomer.CompanyName = "Updated customer 1"; // Send the changes to the database. // Until SaveChanges() is called, the changes are cached on the client side. context.SaveChanges(); |
To remove an instance from a context, use the DeleteObject method of the context. The object is removed from the collection of its type, but not destroyed. To delete the object's data from the database, invoke the SaveChanges method.
DeleteExample |
Copy Code
|
---|---|
context.DeleteObject(newCustomer);
// Send the changes to the database.
// Until SaveChanges() is called, the changes are cached on the client side.
context.SaveChanges();
|
Adding, Modifying, and Deleting Objects