[英]How do I programmatically determine if a type is natively serializable by protobuf-net?
[英]How do I natively translate SqlType to underlying SQL type declaration?
.NET SqlClient中是否有一种方法可以将SqlType转换为实际的SQL类型声明,例如
SqlInt32 -> "int"
SqlGuid -> "uniqueidentifier"
SqlXml -> "xml"
SqlString -> "nvarchar(??)"
不手动做?
澄清:我试图自动重构一些SQL select语句,我需要知道它们返回什么类型。 我打算通过运行以下代码来实现:
using (var connection = new SqlConnection(SqlConnectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = sql;
var reader = command.ExecuteReader(CommandBehavior.SchemaOnly);
for (int i = 0; i < reader.FieldCount; ++i)
{
var type = reader.GetProviderSpecificFieldType(i);
... generate some sql code ...
}
}
所以,一旦我得到了类型,我正在尝试生成一些SQL代码并使用在GetProviderSpecificFieldType中返回的SqlTye,我想看看是否已经有一个我可以使用的函数,它将采用SqlType并给我回复SQL声明
从来没听说过。 由于没有1:1的对应关系(例如, SqlString
可以对应于SQL Server类型char
, nchar
, text
, ntext
, nvarchar
和varchar
),这样的函数必须猜测原始类型是什么,因为这个信息获得SqlString
不再可用。
如果您知道SqlString
始终对应于数据库中的nvarchar(255)
,则可以使用此列表作为起点SqlString
编写此类函数。
你想要实现什么目标? 也许有更好的解决方案来解决你的问题......
我找到了解决方案。 我使用GetSchemaTable来获取SQL类型的详细信息:
private string __type(SqlDataReader reader, int i)
{
var schema = reader.GetSchemaTable();
var row = (from DataRow r in schema.Rows
where (int)r["ColumnOrdinal"] == i
select r).First();
var type = (string) row["DataTypeName"];
if (type == "nvarchar" || type == "varchar" ||
type == "nchar" || type == "char")
{
int maxLength = (int) row["ColumnSize"];
if (maxLength == 2147483647) maxLength = -1;
type += string.Format("({0})", (maxLength > 0) ?
(object) maxLength : (object) "max");
}
return type;
}
不完全重复,但有相反的方向 。
它是一个很多< - >许多映射的问题是完全相同的。
任何全自动的翻译最好是过于热心(例如将任何字符串映射到TEXT列),最糟糕的是以某种微妙的方式错误。
至少它需要依赖于版本,例如它应该使用DateTime还是DateTime2?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.