Abstraction between Database Entities and Objects in C#/VB.net
I've just gotten started with development using Visual Studio (though this can be seen as a more language-generic question), and need done design answers regarding how to suitable relate a Database Entity/Table with an Class in-code.
Currently, I create a class who's attributes or iVars directly correspond to the fields in an Entity.
When I come to fetching all 'Customers from a Table' for example, I run a Select all statement against the database and for each result-row returned, I instantiate a new class Object where I use the Class' default constructor to set the instance variables. (I really wish there was a method like PHP's mysql-fetch-object()?)
I can then add each of these objects to say, a List(of Customer)开发者_运维技巧 and return it.
This doesn't seem like the best way to do it. If I were to change the Database schema, I'd have to reflect those changes in the class also.
Many thanks.
It sounds like what you're looking for is an "object-relational mapper", such as Entity Framework or NHibernate.
Entity Framework is Microsoft's solution, and it's part of the .NET framework (though for the latest version (4.1), you'll need to download that separately). NHibernate is a third-party library. Both should be able to help with what you're trying to do.
Links:
- Entity Framework: http://msdn.microsoft.com/en-us/data/aa937723
- NHibernate: http://nhforge.org/Default.aspx
精彩评论