Entity Framework Core ExecuteSqlCommand delete with SQLite does not work

c# entity-framework-core sqlite


I have the following model:

public class LogData
    public Guid ID { get; set; }
    public string Name { get; set; }

I use Entity Framework Core to save those models to an SQLite database, it works well.

I need to delete from the data (it is dynamic, I can't use objects), so I use the following command:

string command="DELETE FROM LogData WHERE ID IN ('ea53b72a-4ab2-4f88-8f1d-0f96baa7cac7')";

According to the SQLite syntax, it is valid.

Unfortunately, as a result I get back 0, so no row was affected. When I remove the WHERE condition, it deletes the contents of the table.

I have a guessing that as the key column is a Guid and it is stored as a BLOB, the plain SQLite engine can't find it.

So I tried to alter the command to this:

string command="DELETE FROM LogData WHERE HEX(ID) IN ('ea53b72a-4ab2-4f88-8f1d-0f96baa7cac7')";

Also tried this:

string command="DELETE FROM AuditLog WHERE HEX(ID) = 'ea53b72a-4ab2-4f88-8f1d-0f96baa7cac7'";

This, too:

string command="DELETE FROM AuditLog WHERE ID = 'ea53b72a-4ab2-4f88-8f1d-0f96baa7cac7'";

None of those helped.

What should I do about this?

4/15/2019 4:23:22 PM

Accepted Answer

The GUIDs are stored in the database as a binary BLOB meaning you need to pass in a binary value to compare against. To do this you use the X'...' notation. Additionally, you need to convert the endianness of the GUID to little endian. Fortunately, there's a handy extension method here to do your conversion:

public static Guid FlipEndian(this Guid guid)
    var newBytes = new byte[16];
    var oldBytes = guid.ToByteArray();

    for (var i = 8; i < 16; i++)
        newBytes[i] = oldBytes[i];

    newBytes[3] = oldBytes[0];
    newBytes[2] = oldBytes[1];
    newBytes[1] = oldBytes[2];
    newBytes[0] = oldBytes[3];
    newBytes[5] = oldBytes[4];
    newBytes[4] = oldBytes[5];
    newBytes[6] = oldBytes[7];
    newBytes[7] = oldBytes[6];

    return new Guid(newBytes);

And you use it like this:

//The source GUID
var source = Guid.Parse("ea53b72a-4ab2-4f88-8f1d-0f96baa7cac7");
//Flip the endianness
var flippedGuid = source.FlipEndian();

//Create the SQL
var command = $"DELETE FROM AuditLog WHERE ID = X'{flippedGuid.ToString().Replace("-", "")}'";

4/16/2019 6:33:42 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow