一种想法是使用带有表的SQL 管理对象 (SMO)来动态创建强类型。
Server srv = new Server(conn);
Database db = srv.Databases["AdventureWorks"];
foreach (Table table in db.Tables)
{
Console.WriteLine(" " + table.Name);
foreach (Column col in table.Columns)
{
Console.WriteLine(" " + col.Name + " " + col.DataType.Name);
}
}
我已经以这种方式为数据访问层编写了单元测试生成器,您可以使用 DataTypes 列组成类,例如(在线查找更好的实现 - 在 C# 中):
Public Function SQLParameterType(ByVal ParameterDataType As String) As String
ParameterDataType = ParameterDataType.ToUpper
If ParameterDataType.IndexOf("NVARCHAR") > 0 Then
Return "string"
ElseIf ParameterDataType.IndexOf("VARCHAR") > 0 Then
Return "string"
End If
Select Case ParameterDataType
Case Is = "BIGINT"
Return "Int64"
Case Is = "INT"
Return "Int32"
Case Is = "SMALLINT"
Return "Int16"
Case Is = "BIT"
If gIsVBdotNet Then
Return "boolean"
Else
Return "bool"
End If
Case Is = "DATETIME"
Return "DateTime"
Case Is = "DATETIME2"
Return "DateTime"
Case Is = "SMALLDATETIME"
Return "DateTime"
Case Is = "MONEY"
Return "single" 'float
Case Is = "FLOAT"
Return "single" 'float
Case Is = "REAL"
Return "double"
'Case Is = "INT"
' Return "int32"
'Case Is = "INT"
' Return "int32"
Case Else
Return "666"
End Select
End Function
使用这个以模式中立的方式连接到数据库的简单 ORM,您可以将动态生成的类松散地耦合到 dB。.Net 4 中的新动态类型似乎是该应用程序的一个很好的多态数据类型候选者。