Geeks With Blogs
Scott Kuhl Warning: I may have no idea what I am talking about!

Saving your changes to the database is as easy as calling the Save method on the object.

product.Save();

But it's important to know what is happening when you call this method.  The above example does not pass the current user information.  As you'll see later when discussing conventions, SubSonic has the ability to keep some basic history information.  If your tables are setup to record this information, you need to pass either the User ID in integer or GUID format, or the User Name in string format.

product.Save(User.Identity.Name);

If the primary key is a GUID or auto incrementing integer and the object is new, the save process will update the key property in the object.  The save process will also set the IsNew and IsDirty properties to false.

Insert and Update

It is also possible to insert or update data through static class methods.

Product.Insert("Product Name", 1, 1, "10", 10.00, 10, 10, 1, false);
Product.Update("Product Name", 1, 1, "10", 10.00, 10, 10, 1, false);

These methods do all the work of instantiating the object, setting the properties and calling the Save method.  The downside is that neither method returns an autogenerated primary key value.

Deleting

There are two types of deletes: logical and permanent.  A logical delete does not remove the record from the database, rather a column is used to mark the record as deleted.  SubSonic will treat a column named "Deleted" or "IsDeleted" as this flag.  To perform a logical delete, your table must have one of those columns defined as a BIT, then the IsDeleted property will show up on the object that can be set to true.  When the Save method is called, the object will be marked as deleted.  There is also a static method called Delete that takes an object key value and does the same thing.

Product.Delete(product.ProductID);

Note that this example will not work with the default Northwind database since the Products table does not have either type of delete column.  You need to add a "Deleted" column to make it work.

Unfortunately, SubSonic treats this purely as convention when retrieving data.  You will need to filter out deleted records, for example, by using a FetchByParameter method.

Permanent deletes are easier.  Just call the static Destroy method.

Product.Destroy(product.ProductID);

Find the entire series of posts here.

Posted on Wednesday, November 29, 2006 12:51 PM SubSonic | Back to top


Comments on this post: Getting Started with SubSonic - Part 10, Classes - Updating the Database

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Scott Kuhl | Powered by: GeeksWithBlogs.net