Map a dataset to a custom .NET object in ASP.NET

2019-07-30 12:46发布

I want to map data from datatable to custom .NET object. Let's say, I have a .NET object

Public Class MyClass
    Public ID
    Public Prop1
    Public Prop2
End Class

And a corresponding table in the database, which contains columns ID, Prop1 and Prop2.

I want to generate a list of .NET objects from the database. Currently I fill the dataset and map each property individually. Is there any way, to map the database automatically, so the properties would map according to property / column name.

'retreive dataset from db'
DaAdapter.Fill(ds)

'create a new list of my object'
Private l As New List(Of MyClass)

'iterate through dataset (this is the step I want to get rid of - of course'
'it could only work if the property of the MyClass and the column in '
'the database have the same name)'
For Each r As DataRow in ds.Tables(0).Rows
    Dim itm As New MyClass
    itm.ID = r("ID")
    itm.Prop1 = r("Prop1")
    itm.Prop2 = r("Prop2")
    l.Add(itm)
Next

4条回答
老娘就宠你
2楼-- · 2019-07-30 13:23

You can use some sort of Object Relational Mapping (ORM) framework. Entity Framework is one of them

查看更多
beautiful°
3楼-- · 2019-07-30 13:27

I suggest Entity Framework

You can use a database first approach where you just point to your database and it will create the Entities and associations for you.

Its really strait forward, I advise giving it a try

查看更多
beautiful°
4楼-- · 2019-07-30 13:31

There is no direct way , although many tools are available to create classes that exactly resembles database tables called Entity classes. See the following link for more details

Database tables to C# entity classes - generator for FluentNHibernate?

You can also use typeddataset, codesmith tool.

查看更多
Rolldiameter
5楼-- · 2019-07-30 13:32

IMHO. The easiest way is using Linq2Sql

查看更多
登录 后发表回答