Your Problem in the SQL Statement
, it is not valid.
You should divide the statement into two ones:
First Delete Comments
, then delete Posts
Sequence is Important
var deleteComments = new SqlCommand("DELETE Comments FROM Posts INNER JOIN Comments ON Posts.PostId = Comments.PostId WHERE Posts.PostId = @PostId;");
deleteComments.Parameters.AddWithValue("@PostId", postId);
_dataAccess.ExecuteQuery(deleteComments);
var deletePosts = new SqlCommand("DELETE Posts WHERE PostId= @PostId;");
deletePosts.Parameters.AddWithValue("@PostId", postId);
_dataAccess.ExecuteQuery(deletePosts);
The other option, using one statement:
var delete = new SqlCommand("DELETE Comments FROM Posts INNER JOIN Comments ON Posts.PostId = Comments.PostId WHERE Posts.PostId = @PostId; DELETE Posts WHERE PostId= @PostId;");
delete.Parameters.AddWithValue("@PostId", postId);
_dataAccess.ExecuteQuery(delete);
More Explanation:
Using the Following Prepared SQL Script using SQL Studio (SSMS):
CREATE TABLE Posts (PostId INT, PostText varchar(20))
CREATE TABLE Comments (CommentId INT, PostId INT, CommentText varchar(20))
INSERT INTO Posts VALUES (1, 'text')
INSERT INTO Comments VALUES (1,1, 'comment here')
when I run your DELETE statement
DELETE Posts, Comments FROM Posts INNER JOIN Comments ON Posts.PostId = Comments.PostId WHERE Posts.PostId = 1
It gives me the same error
When I run
DELETE Comments FROM Posts INNER JOIN Comments ON Posts.PostId = Comments.PostId WHERE Posts.PostId = 1;
DELETE Posts WHERE PostId = 1;
It works fine.
So the rule of thumb in such cases is to use SSMS (MS SQL Studio) to test your SQL statement first and then implement it in C#.