C# 从类中获取数据库中的Nvarchar长度

C# 从类中获取数据库中的Nvarchar长度,c#,ado.net,C#,Ado.net,我在SQL server中使用类作为表 然后是下面的属性 [Column(Storage = "_new_name", DbType = "nvarchar (2000)")] public string new_name { get { return _new_name; } set { _new_name = value; } } 所以。我可以用C# 现在是2000年 谢谢如果不进行反思,你就很难做到这一点。属性是元数据,因此它们只使用各种进程所需的附加信息来装饰代码。在您的情况下,ORM

我在SQL server中使用类作为表

然后是下面的属性

[Column(Storage = "_new_name", DbType = "nvarchar (2000)")]
public string new_name { get { return _new_name; } set { _new_name = value; } }
所以。我可以用
C#

现在是2000年


谢谢

如果不进行反思,你就很难做到这一点。属性是元数据,因此它们只使用各种进程所需的附加信息来装饰代码。在您的情况下,ORM需要识别哪些属性映射到哪个列

假设您有这样一个类:

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;
        }
    }
}
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);
    }
}
可以从属性中读取属性值,如下所示:

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;
        }
    }
}
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);
    }
}
var properties=typeof(TestTable).GetProperties();
var attributesPerProperty=新字典();
foreach(属性中的var propertyInfo)
{
var attribute=System.attribute.GetCustomAttributes(propertyInfo.FirstOrDefault();
if(属性为ColumnAttribute)
{
var columnAttribute=(columnAttribute)属性;
attributesPerProperty.Add(propertyInfo.Name,columnAttribute.DbType);
}
}

这不是一种理想的方法,我刚刚给出了一个粗略的示例,但如果您真的需要从类中读取此类信息,以上内容将帮助您达到目的。

有一个专门针对代码格式设置的标记。请用它。