What are the advantages of using POCOs over DataTables?
In a data access layer, that queries a database and returns an enumerable object of results, what are the advantages of returning say a list of Dog objects with properties Name, Age, etc, instead of a Da开发者_StackOverflow社区taTable that has columns like "Name", "Age", etc ?
A few:
- Type safety
- Serialisation not just to XML but JSON, binary ...
- Readability
- More light-weight
- Ability to add behaviours
- Ability to define DataAnnotation and validation logic
- Ability to use ORMs
If you use a plain DataTable, you end up with magic strings everywhere (even if you use constants). The code to extract the values ends up being clumsy and error-prone, basically because you end up having to supply data (names, expressions etc) where you're really trying to express code.
Any time you call DataTable.Select
or DataTable.Sort
, or access the DataRow
indexer, imagine how much less fluff - and less potential for error - there would be if you were using a strongly-typed model. This could be a strongly-typed data set of course, but even then I find there's generally less friction with POCOs.
Additionally, POCOs typically require less fluff to test code with than DataTables.
If you use objects instead of DataTables, you get strongly typed results and makes the code using the data a lot cleaner. You won't have to have all sorts of strings in order to access what should just be a property on an object.
Also, if you use an ORM tool like NHibernate, you can map from the database directly to your objects without having to manually call out to the database and deal with SqlCommands, etc..
It separates your business logic from your persistence layers.
So your 'Dog' object, and most of the code that uses it, can just concern itself with Dogs and Doginess, and not worry about which ever flavour of data access is fashionable this week.
精彩评论