【问题标题】:Is there a class that automatically converts .NET framework types to PostgreSQL types?是否有自动将 .NET 框架类型转换为 PostgreSQL 类型的类?
【发布时间】:2015-10-03 14:12:56
【问题描述】:

为了编写 sql 查询,我需要能够采用 .NET 类型并获取 PostgreSQL 类型的字符串。例如,我需要从

typeof(int) --> "int"

这很棘手,因为 typeof(int) 是 System.Int32。我找到了一些表格,such as this one,但我想知道是否有一个类可以自动完成,而不必自己编写所有映射。

【问题讨论】:

    标签: c# sql .net type-systems


    【解决方案1】:

    可能会起作用:

    public static class DotNetTypeToPostgreSqlType
    {
        public static string GetPostgreType(object o)
        {
            if (o is Int64)
            {
                return "int8";
            }
            if (o is Boolean)
            {
                return "bool";
            }
            if (o is Byte[])
            {
                return "bytea";
            }
            if (o is DateTime)
            {
                return "date";
            }
            if (o is Double)
            {
                return "float8";
            }
            if (o is Int32)
            {
                return "int4";
            }
            if (o is Decimal)
            {
                return "money";
            }
            if (o is Decimal)
            {
                return "numeric";
            }
            if (o is Single)
            {
                return "float4";
            }
            if (o is Int16)
            {
                return "int2";
            }
            if (o is String)
            {
                return "text";
            }
            if (o is DateTime)
            {
                return "time";
            }
            if (o is DateTime)
            {
                return "timetz";
            }
            if (o is DateTime)
            {
                return "timestamp";
            }
            if (o is DateTime)
            {
                return "timestamptz";
            }
            if (o is TimeSpan)
            {
                return "interval";
            }
            if (o is String)
            {
                return "varchar";
            }
            if (o is IPAddress)
            {
                return "inet";
            }
            if (o is Boolean)
            {
                return "bit";
            }
            if (o is Guid)
            {
                return "uuid";
            }
            if (o is Array)
            {
                return "array";
            }
            throw new NotImplementedException("Unknown postgresql type");
        }
    }
    

    【讨论】:

    • 哈哈谢谢你帮我写出来。我想没有正式的课程,这有点烦人,但这很好用。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2013-11-05
    • 2022-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多