2014-01-19 35 views
-1

我想要從MSSQL輕鬆地綁定到ASP.NET中的VB。 我願做這樣的事情...從sql到使用字符串名稱的變量進行綁定

Public Class Address 
    Public Shared name As String 
    Public Shared address1 As String 
    Public Shared address2 As String 
    Public Shared city As String 
    Public Shared state As String 
    Public Shared phone As String 
    Public Shared email As String 
End Class 

,我想從像山坳加載這些變量。在MSSQL 名稱,以便像...

for i = 0 to reader.fieldcount -1 
address.(reader.getname(i)) = reader(i) 
next 

我怎麼會做VB或C#這樣的事情?

回答

1

你必須依靠反射如下:

Type type = address.GetType(); 

for (int i=0; i < reader.FieldCount; i++) 
{ 
    var property = type.GetProperty(reader.GetName(i)); 

    var setMethod = property.GetSetMethod(); 

    setMethod.Invoke(address, new object[]{reader[i]}); 
} 
+0

我也使用字典var而不是特定的變量解決了這個問題。 – Ishey4

1

我會用一個輕量ORM像Dapper爲我做到這一點。這有點神奇,會爲你節省大量的時間。對於CRUD操作,也有各種Dapper擴展。