Linq Deletes



You can use the goodness that is the Linq syntax to delete data from your database. It's important to note that SubSonic IS NOT AN ORM - it's a query tool (subtle difference) and therefore it doesn't do object tracking. There's nothing stopping you from creating a T4 template to do just this - but out of the box SubSonic is not designed this way.

Typically, ORM's will track the changes to your object and will "flush" these changes to the database when you tell it to (this is the way Linq to Sql works). This is fine and dandy if you like working that way - but we think this is a Big Lie.

The web is a stateless medium - this sort of "contextual tracking" is just not the Real World and we don't drink that beer.


Make sure you setup SubSonic by adding a reference, setting up your DB connection, and then adding the templates to your project.

Simple Deletes

You can work with the Query Surface directly to delete data from your database:

var db = Northwind.DB.CreateDB();
db.Delete<Product>(x => x.ProductID == 1).Execute();

This creates the following SQL:

DELETE FROM [dbo].[Products] 
WHERE [dbo].[Products].[ProductID] = @0

Using the Repository

There are 2 ways to delete using the IRepository generated for you:

var repo = new NorthwindRepository<Product>();
var repo = new NorthwindRepository<Product>();
var product = repo.GetByKey(1);

Multiple Deletes

You can delete multiple objects transactionally using Batch Query:

var repo = new NorthwindRepository<Product>();
var queue = new List<Product>();
for (int i = 1; i < 10; i++) {
    var product = repo.GetByKey(i);