如何在流利的迁移器中捕获特定的SQL异常?

时间:2019-05-31 07:45:35

标签: c# sql-server fluent-migrator

我正在编写迁移,该迁移应删除重复的行,但是可能会使用某些ID,因此对于这种情况,应将记录设置为非活动状态。我已经编写了应该运行的迁移方法:)但是我想知道是否可以捕获特定的ForeignKeyException?我仅在删除行时发生外键错误时才尝试将active设置为0。 sql服务器上的数据库。

迁移

[Migration(201905311022)]
public class _201905311022_RemoveDuplicatesFromCarrierLookUp : Migration
{
    private const string row_number = "row_number";
    private const string CTE = "CTE";
    private const string LookUp_Carrier = "LookUp_Carrier";
    private const string CarrierId = "CarrierId";
    private const string Carrier = "Carrier";
    private readonly string WithCte = $@"
WITH CTE AS
(SELECT {Carrier}, {CarrierId}, ROW_NUMBER() OVER(PARTITION BY {Carrier} 
ORDER BY {CarrierId}) as {row_number} FROM {LookUp_Carrier})";

    public override void Up()
    {
        try
        {
            RemoveRecordsWithSameName();
        }
        catch(Exception foreignKeyConstrain)
        {
            MakeRecordsWithSameNameInActive();
        }
    }

    private void MakeRecordsWithSameNameInActive()
    {
        Execute.Sql($@"{WithCte}
UPDATE {LookUp_Carrier}
SET Active = 0
WHERE {CarrierId} in (SELECT {CarrierId} FROM {CTE} WHERE {row_number} <> 1)");
    }

    private void RemoveRecordsWithSameName()
    {
        Execute.Sql($@"{WithCte}
  DELETE FROM {LookUp_Carrier} WHERE {CarrierId} IN (SELECT {CarrierId} FROM {CTE} WHERE {row_number} <> 1)");
    }

    public override void Down()
    {
        Console.WriteLine("Rollback for data manipulation wasn't implemented");
    }
}

1 个答案:

答案 0 :(得分:1)

您可以像这样处理它:

$ cat case.sh && echo -e "#################\n" && bash case.sh ws-23.host.com
#!/bin/bash
SERVER=$1;
echo $SERVER | egrep "ws-[0-9]+\.host\.com";
case $SERVER in
  $(awk '{a=0}/ws-[0-9]*.host.com/{a=1}a' <<<${SERVER}))echo "Web Server";;
  $(awk '{a=0}/db-[0-9]*.host.com/{a=1}a' <<<${SERVER}))echo "DB Server";;
  $(awk '{a=0}/bk-[0-9]*.host.com/{a=1}a' <<<${SERVER}))echo "Backup Server";;
  *)echo "Unknown server";;
esac

#################

ws-23.host.com
Web Server