如何将 C# 数据类型“转换”为 SQL Server 数据类型(SqlDbType
是已知的)
i.e:
C# -> "String"
SQL Server -> N'String'
尝试这个:
它是一个 Extension 类,因此您要在文件上添加以下方法:
using Utility;
这是代码:
using System;
using System.Data;
using Microsoft.SqlServer.Server;
namespace Utility
{
public static class TypeExtension
{
public static SqlDbType ToSqlDbType(this Type clrType)
{
var s = new SqlMetaData("", SqlDbType.NVarChar, clrType);
return s.SqlDbType;
}
public static Type ToClrType(SqlDbType sqlType)
{
switch (sqlType)
{
case SqlDbType.BigInt:
return typeof (long?);
case SqlDbType.Binary:
case SqlDbType.Image:
case SqlDbType.Timestamp:
case SqlDbType.VarBinary:
return typeof (byte[]);
case SqlDbType.Bit:
return typeof (bool?);
case SqlDbType.Char:
case SqlDbType.NChar:
case SqlDbType.NText:
case SqlDbType.NVarChar:
case SqlDbType.Text:
case SqlDbType.VarChar:
case SqlDbType.Xml:
return typeof (string);
case SqlDbType.DateTime:
case SqlDbType.SmallDateTime:
case SqlDbType.Date:
case SqlDbType.Time:
case SqlDbType.DateTime2:
return typeof (DateTime?);
case SqlDbType.Decimal:
case SqlDbType.Money:
case SqlDbType.SmallMoney:
return typeof (decimal?);
case SqlDbType.Float:
return typeof (double?);
case SqlDbType.Int:
return typeof (int?);
case SqlDbType.Real:
return typeof (float?);
case SqlDbType.UniqueIdentifier:
return typeof (Guid?);
case SqlDbType.SmallInt:
return typeof (short?);
case SqlDbType.TinyInt:
return typeof (byte?);
case SqlDbType.Variant:
case SqlDbType.Udt:
return typeof (object);
case SqlDbType.Structured:
return typeof (DataTable);
case SqlDbType.DateTimeOffset:
return typeof (DateTimeOffset?);
default:
throw new ArgumentOutOfRangeException("sqlType");
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)