반응형

Database의 Column명과 구조체의 변수명이 다른경우 Column Attribute 값을 지정후 읽어서 사용하는 방법

// Define your structure with properties and apply the Column attribute
struct MyStruct
{
    [Column("my_column")]
    public int MyProperty { get; set; }
}

class Program
{
    static void Main()
    {
        // Create an instance of your structure
        MyStruct myInstance = new MyStruct();

        // Get the type of your structure
        Type structType = myInstance.GetType();

        // Get the property information using reflection
        PropertyInfo propertyInfo = structType.GetProperty("MyProperty");

        // Get the Column attribute applied to the property
        ColumnAttribute columnAttribute = (ColumnAttribute)propertyInfo.GetCustomAttribute(typeof(ColumnAttribute));

        // Check if the attribute is present
        if (columnAttribute != null)
        {
            // Access the attribute value
            string columnName = columnAttribute.Name;

            // Print the attribute value
            Console.WriteLine($"Column name: {columnName}");
        }
        else
        {
            Console.WriteLine("Column attribute not found");
        }
    }
}
반응형

+ Recent posts