Search code examples
c#sqlsql-serverservicestackormlite-servicestack

Using ServiceStack OrmLite to delete rows with condition in other table


I have the following tables in the database:

Table C    Table B    Table A
-------    -------    -------
Id         Id         Id
BId        AId

The BId column is a foreign key to TableB. AId is a foreign key to TableA. I want to delete all rows from Table C that is connected to a row in TableA. The following SQL (used in SQL Management Studio) does the trick:

DELETE [ns].[TableC]
  FROM [ns].[TableC] c
  JOIN [ns].[TableB] b ON c.[BId] = b.[Id]
  WHERE b.[AId] = 530
GO

I tried using the following code:

var query = connection.From<TableC>()
            .Join<TableC, TableB>((c, b) => c.BId == b.Id)
            .Where<TableB>(b => b.AId == 530);    
connection.Delete<TableC>(query);

But this results in an exception and from calling GetLastSql() I get:

DELETE FROM "ns"."TableC" WHERE ("ns"."TableB"."AId" = @0)

How can I use ServiceStack OrmLite to accomplish this delete?


Solution

  • Support for DELETE TABLE JOINS were just recently added to OrmLite and is available from v4.5.1 that's now available on MyGet.