C# SQL Create Trigger命令在MySQL工作台中运行良好,但在通过实体框架调用时出错
我有以下代码来创建SQL设置触发器,而不是准备好的语句C# SQL Create Trigger命令在MySQL工作台中运行良好,但在通过实体框架调用时出错,c#,mysql,entity-framework,triggers,C#,Mysql,Entity Framework,Triggers,我有以下代码来创建SQL设置触发器,而不是准备好的语句 commandList.Add($"DROP TRIGGER if exists `{tableName}_after_insert`;"); commandList.Add($"delimiter $$" + Environment.NewLine + $"CREATE TRIGGER `{tableName}_after_insert` AFTER INSERT" + Environment.NewLine + $"ON
commandList.Add($"DROP TRIGGER if exists `{tableName}_after_insert`;");
commandList.Add($"delimiter $$" + Environment.NewLine +
$"CREATE TRIGGER `{tableName}_after_insert` AFTER INSERT" + Environment.NewLine +
$"ON `{tableName}`" + Environment.NewLine +
"FOR EACH ROW BEGIN" + Environment.NewLine +
"Insert into HashEntry(TableName, TableRowId, TokenValue)" + Environment.NewLine +
$"select '{tableName}', n.{tableKey}, 'tokenValue' from NEW n;" + Environment.NewLine +
"END;" + Environment.NewLine +
"$$" + Environment.NewLine +
"delimiter ;");
//then some unrelated code until we execute
foreach (var command in commandList)
{
Database.ExecuteSqlCommand(command);
}
这将创建以下在工作台和实体框架中工作的SQL
DROP TRIGGER if exists `MyTable_after_insert`;
这只在Workbench中直接工作
delimiter $$
CREATE TRIGGER `MyTable_after_insert` AFTER INSERT
ON `MyTable`
FOR EACH ROW BEGIN
Insert into HashEntry(TableName, TableRowId, TokenValue)
select 'MyTable', n.Id, 'tokenValue' from NEW n;
END;
$$
delimiter ;
这会产生以下错误
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'delimiter $$
CREATE TRIGGER `MyTable_after_insert` AFTER INSERT
我不确定为什么它会直接在Workbench中工作,但不会通过EF调用相同的命令
有什么想法吗?分隔符$$是只有MySQL工作台才能理解的特殊语法。在使用MySqlCommand对服务器执行命令时,不需要这样做。只需直接执行SQL:
commandList.Add($@"CREATE TRIGGER `{tableName}_after_insert` AFTER INSERT
ON `{tableName}`
FOR EACH ROW BEGIN
Insert into HashEntry(TableName, TableRowId, TokenValue)
select '{tableName}', n.{tableKey}, 'tokenValue' from NEW n;
END;");
请注意,我正在使用以避免与Environment.NewLine的所有连接。可能是因为您在字符串中使用了$$,如果您将其更改为其他内容,该怎么办?它好像不像delimeterI用三个下划线试过的那样,而且也不起作用。现在这似乎非常明显。成功了,谢谢你。