Entity Framework Core ExecuteSqlCommand delete with SQLite 不



我有以下模型:

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

我使用实体框架核心将这些模型保存到SQLite数据库中,它运行良好。

我需要从数据中删除(它是动态的,我不能使用对象(,所以我使用以下命令:

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

根据 SQLite 语法,它是有效的。

不幸的是,结果我得到了 0,所以没有行受到影响。当我删除WHERE条件时,它会删除表的内容

我有一个猜测,由于键列是一个Guid并且它存储为BLOB,普通的SQLite引擎找不到它。

所以我试图将命令更改为:

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

还尝试了这个:

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

这也是:

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

这些都无济于事。

我该怎么办?

GUID 作为二进制BLOB存储在数据库中,这意味着您需要传入二进制值进行比较。为此,请使用X'...'表示法。此外,还需要将 GUID 的字节序转换为小端序。幸运的是,这里有一种方便的扩展方法来进行转换:

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);
}

你像这样使用它:

//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("-", "")}'";
context.Database.ExecuteSqlCommand(command);

最新更新