获取DB DataType ServiceStack Ormlite

时间:2016-05-20 08:13:52

标签: database types ormlite-servicestack

POCO类是否有办法获取各种属性的实际DB数据类型? 例如:让我们假设POCO类

public  class Product : IHasId<int>
{
    [Alias("id")]
    [Required]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description  { get; set; }
}

字段名称和描述可以是数据库(SQL Server)中的Varchar(n)或Text。是否可以从POCO属性中获取实际的DB DataType?

1 个答案:

答案 0 :(得分:3)

OrmLite希望底层的RDBMS Schema列定义能够在TypeConverter中指定,您可以使用它来获取:

var converter = OrmLiteConfig.DialectProvider.GetStringConverter();
var columnDef = converter.ColumnDefinition;

要获得实际的列定义,您需要使用自定义SQL来查询SQL Server

var sql = @"select COLUMN_NAME, data_type + 
    case
        when data_type like '%text' or data_type like 'image' or data_type like 'sql_variant' or data_type like 'xml'
            then ''
        when data_type = 'float'
            then '(' + convert(varchar(10), isnull(numeric_precision, 18)) + ')'
        when data_type = 'numeric' or data_type = 'decimal'
            then '(' + convert(varchar(10), isnull(numeric_precision, 18)) + ',' + convert(varchar(10), isnull(numeric_scale, 0)) + ')'
        when (data_type like '%char' or data_type like '%binary') and character_maximum_length = -1
            then '(max)'
        when character_maximum_length is not null
            then '(' + convert(varchar(10), character_maximum_length) + ')'
        else ''
    end as COLUMN_DEFINITION
FROM information_schema.columns";

using (var db = dbFactory.OpenDbConnection())
{
    var results = db.Dictionary<string,string>(sql + " WHERE table_name = 'Product'");

    var nameColumnDef = results["Name"]; //= varchar(8000)

    //Or print out all column definitions for each field with:
    results.PrintDump();
    /*
    {
        Id: int,
        Name: varchar(8000)
        ...
    }
    */
}