C# 클래스로부터 데이터베이스 테이블을 자동 생성하는 방법

데이터베이스 테이블을 수동으로 만드는 것은 지루한 작업이 될 수 있으며, 특히 많은 클래스가 있는 경우 더욱 그렇습니다. 길고 복잡한 SQL 스크립트를 작성하지 않고 빠르게 테이블을 생성해야 하는 상황이라면, 당신은 올바른 곳에 있습니다. 이 블로그 포스트에서는 리플렉션과 약간의 코딩 마법을 사용하여 C# 클래스에서 데이터베이스 테이블을 자동 생성하는 솔루션을 제공합니다.

문제

여러 C# 클래스가 있다고 상상해 보세요. 애플리케이션의 성장과 함께 이들 각 클래스에 해당하는 데이터베이스 테이블을 생성해야 합니다. 이러한 테이블을 수동으로 만들면 피로감이 클 뿐만 아니라 오류가 발생할 가능성도 높습니다. 다음은 간단한 C# 클래스의 예입니다:

class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private int property2;
    public int Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}

이 클래스에서 필요한 SQL 문은 다음과 같아야 합니다:

CREATE TABLE Foo
(
    Property1 VARCHAR(500),
    Property2 INT
)

또한, System.Management.ManagementObject와 같은 복합형 타입을 클래스 내에서 다루는 것은 복잡성을 더욱 증가시킬 수 있습니다. 이는 수정된 버전의 Foo 클래스에서도 나타납니다.

해결책

1단계: 환경 설정

먼저, C#에서 콘솔 애플리케이션을 생성해야 합니다. 이 애플리케이션은 클래스를 검사하고 이에 해당하는 SQL 스크립트를 생성할 것입니다. 코드가 작동하는 방식은 다음과 같습니다:

  1. 어셈블리 로드: 리플렉션을 사용하여 C# 클래스가 포함된 어셈블리를 로드합니다.
  2. 타입 반복: 어셈블리 내의 각 클래스를 반복하며 그 속성을 수집합니다.
  3. SQL 스크립트 생성: 각 클래스에 대해 속성과 타입을 기반으로 CREATE TABLE SQL 스크립트를 생성합니다.

2단계: 코드 구현

다음은 필요에 맞게 수정할 수 있는 구현의 핵심部分입니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace TableGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            List<TableClass> tables = new List<TableClass>();

            Assembly assembly = Assembly.LoadFile(args[0]);
            Type[] types = assembly.GetTypes();

            foreach (Type type in types)
            {
                TableClass tableClass = new TableClass(type);
                tables.Add(tableClass);
            }

            foreach (TableClass table in tables)
            {
                Console.WriteLine(table.CreateTableScript());
                Console.WriteLine();
            }
        }
    }

    public class TableClass
    {
        private List<KeyValuePair<string, Type>> fields = new List<KeyValuePair<string, Type>>();
        public string ClassName { get; set; }

        private Dictionary<Type, string> dataMapper = new Dictionary<Type, string>
        {
            { typeof(int), "BIGINT" },
            { typeof(string), "NVARCHAR(500)" },
            // 필요에 따라 매핑 추가
        };

        public TableClass(Type type)
        {
            ClassName = type.Name;
            foreach (PropertyInfo property in type.GetProperties())
            {
                fields.Add(new KeyValuePair<string, Type>(property.Name, property.PropertyType));
            }
        }

        public string CreateTableScript()
        {
            var script = new System.Text.StringBuilder();
            script.AppendLine($"CREATE TABLE {ClassName}");
            script.AppendLine("(");
            script.AppendLine("\t ID BIGINT,");

            for (int i = 0; i < fields.Count; i++)
            {
                var field = fields[i];
                script.Append($"\t {field.Key} {(dataMapper.ContainsKey(field.Value) ? dataMapper[field.Value] : "BIGINT")}");

                if (i != fields.Count - 1)
                {
                    script.Append(",");
                }
                script.AppendLine();
            }

            script.AppendLine(")");
            return script.ToString();
        }
    }
}

3단계: 코드 실행

데이터 클래스가 포함된 어셈블리를 로드한 후, 코드를 실행하면 됩니다. 그러면 다음과 유사한 SQL 스크립트가 생성됩니다:

CREATE TABLE FakeDataClass
(
    ID BIGINT,
    AnInt BIGINT,
    AString NVARCHAR(255)
)

CREATE TABLE FKClass
(
    ID BIGINT,
    AFKInt BIGINT
)

추가 생각

  • 필터링을 위한 속성: 클래스에 커스텀 속성인 [SqlTable]을 추가하여 지정된 클래스만 테이블로 변환되도록 고려해 보세요.
  • 개선 사항: 코드는 더 최적화되고 리팩토링될 수 있습니다. 예를 들어, 외래 키 관계 처리는 다소 기본적이므로 추가 로직을 통해 개선될 수 있습니다.

이 솔루션은 C# 클래스 구조를 기반으로 SQL 테이블 생성을 자동화하기 위한 견고한 시작점을 제공합니다. 행복한 코딩 되세요!