The best way to organize work with database

I wonder what is the best way to organize working with database from C# code.

I used to have different approaches for that:

  • Each object has Save, Update and Delete methods, which implemented all the logic.
  • There was some static class that has static methods Get, GetList, Update -- almost the same method as previous, but database logic was extracted from data domain class.
  • 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.


    存储库模式是构建数据访问逻辑的一种非常常见的方式。

    链接地址: http://www.djcxy.com/p/82132.html

    上一篇: 如何选择DI容器?

    下一篇: 组织数据库工作的最佳方式