Friday, August 22, 2008

[Tutorial] ADO.NET Entity Framework
Part 5 - Updating data in the data source

The last parts concentrated on how to query data from the DB using the Entity Framework. This part shows how to update data in the DB. You need to have the correctly configured project from the last part as prerequisite for the following example.

  • Update the value of the property that you want to change (product standard cost for the example). Then call the SaveChanges() method. That's it! You now already have updated the value in the DB.

  • Concurrency checks on properties can be activated. If there are concurrency problems on these properties (someone has modified the data at the same time you did) then there will be an optimistic concurrency exception.
  • No more hassle with SQL statements that need to be modified anymore. The entity data model just needs to be updated if the data structure has changed.
  • Custom verification logic to assure that updated data is conforming to certain business rules can be applied. The auto-generated classes in the data model are already prepared for this purpose. They are providing partial classes and partial methods that can be extended.

  • Add a new class to the project (AdventureWorksEntities.cs for the example).

  • Modify the code within the new class to implement the partial class Product and the partial method OnStandardCostChanging(...). Then add the constraint that the standard cost cannot be less than 0.

  • Assign a value that is less than 0 in the main function of the project.

  • Run the application and you will get the expected exception.


No comments: