Get Nvarchar length in Database From Class

415 Views Asked by At

I have Class use as Table in SQL server

Then properties below

[Column(Storage = "_new_name", DbType = "nvarchar (2000)")]
public string new_name { get { return _new_name; } set { _new_name = value; } }

So. Can I get Length From my Class using C#

In this case It's 2000

Thank

1

There are 1 best solutions below

0
Yannick Meeus On BEST ANSWER

You can't easily, without resorting to Reflection. Attributes are meta-data, so they only decorate code with additional information required for various processes. In your case, for your ORM to identify which property maps to which column.

Assuming you have a class like this:

public class TestTable
{
    private string _new_name;
    private string _address;

    [Column(Storage = "_new_name", DbType = "nvarchar (2000)")]
    public string new_name {
        get
        {
            return _new_name;
        }
        set
        {
            _new_name = value;
        }
    }

    [Column(Storage = "_address", DbType = "nvarchar (5000)")]
    public string address {
        get
        {
            return _address;
        }
        set
        {
            _address = value;
        }
    }
}

You can read the attribute values from the properties like this:

var properties = typeof(TestTable).GetProperties();

var attributesPerProperty = new Dictionary<string, string>();
foreach (var propertyInfo in properties)
{
    var attribute = System.Attribute.GetCustomAttributes(propertyInfo).FirstOrDefault();

    if(attribute is ColumnAttribute)
    {
        var columnAttribute = (ColumnAttribute)attribute;
        attributesPerProperty.Add(propertyInfo.Name, columnAttribute.DbType);
    }
}

It's not an ideal way of doing things, and I've just given a rough example but if you really, really need to read this kind of information from your classes, the above will get you there.