2009-07-01 3 views
0

마이그레이션을 많이 사용하며 (MySQL 만 해당) SubSonic 마이그레이션은 CreateForeignKey에서 상위 및 마스터 열을 정의 할 수 있으므로 하위 클래스에서 업데이트/삭제 작업을 정의 할 수 없습니다. FK 관계.SubSonic 2 마이그레이션 Addon : MySQL 특정 ForeignKey 마이그레이션 단계 만들기

하지만 부모 레코드를 삭제하면 자식 테이블의 모든 레코드를 null로 설정해야하는 FK 관계를 정의해야하는 경우가 많이 있습니다 (기본값은 삭제).

나를 위해이 작업을 수행하는 약간의 기능을 사용합니다. 그러나 이것이 전적으로 MySQL과 관련되어 있기 때문에 (DB 독립적 인) 마이그레이션을 의미하는 아이디어가 깨지기 때문에이를 위해 패치를 제공하지 않기로했습니다. 그래서 여기에 코드 스 니펫을 게시합니다.

하지만 누군가가 이것을 필요로한다면. 자유롭게 사용하십시오.
단 하나의 단점이 있습니다. sonic.exe가 코드 파일을 읽고 즉시 사용하기 때문에 코드를 사용하는 모든 마이그레이션에 코드를 붙여 넣어야합니다.

답변

0

여기 내가 이것을 사용하는 샘플 마이그레이션이 있습니다. down 메서드에서 기존의 "DropForeignKey (...)"메서드를 사용할 수 있습니다. 그 이유는 이름이 동일하기 때문입니다.

using System; 
using System.Collections.Generic; 
using System.Text; 
using SubSonic; 

namespace MyNameSpace.Migrations 
{ 

    public class Migration001 : Migration 
    { 

     public override void Up() 
     { 
      TableSchema.Table parent = GetTable("parent"); 
      TableSchema.Table child = GetTable("child"); 

      CreateForeignKeyMySQL(parent.GetColumn("id"), child.GetColumn("parent_id"), 
       CreateForeignKeyAction.SetNull, CreateForeignKeyAction.Restrict); 

      base.Up(); 
     } 

     public override void Down() 
     { 
      DropForeignKey(parent.GetColumn("id"), child.GetColumn("parent_id")); 

      base.Down(); 
     } 

     #region foreign key helper function 

     public enum CreateForeignKeyAction 
     { 
      Cascade, 
      Restrict, 
      SetNull, 
      NoAction 
     } 

     private String CreateForeignKeyActionValue(CreateForeignKeyAction action) 
     { 
      switch (action) 
      { 
       case CreateForeignKeyAction.Cascade: 
        return "CASCADE"; 
       case CreateForeignKeyAction.Restrict: 
        return "RESTRICT"; 
       case CreateForeignKeyAction.SetNull: 
        return "SET NULL"; 
       case CreateForeignKeyAction.NoAction: 
        return "NO ACTION"; 
       default: 
        return "CASCADE"; 
      } 
     } 

     public void CreateForeignKeyMySQL(
      TableSchema.TableColumn oneTable, TableSchema.TableColumn manyTable, 
      CreateForeignKeyAction onDelete, CreateForeignKeyAction onUpdate) 
     { 

      String sqlAppend = String.Format(" ON DELETE {0} ON UPDATE {1}", 
       CreateForeignKeyActionValue(onDelete), CreateForeignKeyActionValue(onUpdate)); 

      SubSonic.MySqlGenerator generator = new SubSonic.MySqlGenerator(null); 
      String sqlCommand = 
       System.Text.RegularExpressions.Regex.Replace(
        generator.BuildForeignKeyStatement(oneTable, manyTable), ";?$", sqlAppend 
       ); 

      Execute(sqlCommand); 
     } 

     #endregion 

    } 

} 
관련 문제