gpt4 book ai didi

database - 获取数据库数据类型 ServiceStack Ormlite

转载 作者:搜寻专家 更新时间:2023-10-30 22:09:06 25 4
gpt4 key购买 nike

有没有办法从 POCO 类中获取各种属性的实际数据库数据类型?例如:让我们假设 POCO 类

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

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

最佳答案

OrmLite 期望底层 RDBMS 架构列定义是 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)
...
}
*/
}

关于database - 获取数据库数据类型 ServiceStack Ormlite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37341404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com