简体   繁体   中英

Binding From sql to variables using the string name

i am trying to easily bind from MSSQL to ASP.NET in VB. I would like to do something like this...

  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

and i want to load these variables from like col. names in MSSQL so something like...

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

how would i do something like this in VB or C#?

You have to rely on Reflection as follows:

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]});
}

I would use a light-weight ORM like Dapper to do this for me. It's a little bit of magic that will save you a tonne of time. There are also various Dapper extensions for CRUD operations also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM