BitKFu
BitKFu

Reputation: 3697

EF Does not execute delete command

I'm using the entity framework as my data access layer. But for some tasks (e.g. batch deleting), I want to use raw SQL commands.

But at this point EF surprises me, because it seems to execute the DML, but does not do anything.

If I run the sql directly, it executes and deletes the data as expected. So what do I do wrong?

    using (var db = new MyDbContext())
    {
        var sqlTime = string.Concat("DELETE FROM SYNCING_CONTENT WHERE ID in (SELECT SyncContent_Id FROM SYNCING WHERE EXPIRATION < GETDATE());");
        var deleted = db.Database.ExecuteSqlCommand(sqlTime);

        return deleted;
    }

EDIT:

    using (var db = new MyDbContext())
    {
        const string SQL_TIME = "DELETE FROM SYNCING_CONTENT WHERE ID in (SELECT SyncContent_Id FROM SYNCING WHERE EXPIRATION < GETDATE())";
        var deleted = db.Database.ExecuteSqlCommand(SQL_TIME);

        return deleted;
    }

Upvotes: 3

Views: 1469

Answers (1)

Nicholas Murray
Nicholas Murray

Reputation: 13533

Try removing the ; from your SQL string.

Also the issue may be due to the passing of GETDATE() in your sql string, I know this an issue if you pass it as a sql parameter.

Try

const string SQL_TIME = @"DELETE FROM SYNCING_CONTENT WHERE ID in (SELECT SyncContent_Id FROM SYNCING WHERE EXPIRATION < {0})";
db.Database.ExecuteSqlCommand(SQL_TIME, DateTime.Now);

Upvotes: 1

Related Questions