我有以下模型:
@Id
我使用 Entity Framework Core 将这些模型保存到 SQLite 数据库中,效果很好。
我需要从数据中删除(它是动态的,我不能使用对象),所以我使用以下命令:
public class LogData
{
public Guid ID { get; set; }
public string Name { get; set; }
}
根据SQLite syntax,它是有效的。
不幸的是,结果我回到0,所以没有一行受到影响。
当我删除string command="DELETE FROM LogData WHERE ID IN ('ea53b72a-4ab2-4f88-8f1d-0f96baa7cac7')";
context.Database.ExecuteSQLCommand(command);
条件时,它删除了表的内容。
我猜想,由于键列是WHERE
并存储为Guid
,普通的SQLite引擎找不到它。
所以我尝试将命令更改为此:
BLOB
也尝试过:
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);
这些都没有帮助。
我该怎么办?
答案 0 :(得分:2)
GUID以二进制BLOB
的形式存储在数据库中,这意味着您需要传递二进制值进行比较。为此,请使用X'...'
表示法。此外,您需要将GUID的endianness转换为little endian。幸运的是,有一个方便的扩展方法here可以完成转换:
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);