I wonder what is the best way to organize working with database from C# code.
I used to have different approaches for that:
Now I think it will be great to have some non-static classes for each of datadomain class I need to store somewhere, that will do the storage.
What is the best way to do it? Are there any good libraries that provide good API for storing objects?
Use a Object/Relation Mapper (ORM). My personal favorite is nhibernate. Use Entity Framework if you want a Microsoft product.
ORM's usually implement UnitOfWork and Repository patterns which makes it easier for you to handle database operations and follow the Single Responsibility Principle.
You also mentioned singletons. I would avoid them if possible. Have you tried to unit test a class that uses singletons? It's impossible unless the singleton is a proxy for the actual implementation. The easiest way to remove singletons is to invert dependencies by using dependecy injection. There are several containers available.
The recommended way to work with databases these days is through an ORM.
Look at nHibernate (community project) and Entity Framework (Microsoft provided) for some of the most popular choices for .NET, though there are many many more.
These are libraries that provide you with all the data access that you need, with some configuration needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With