The best way to organize work with the database

I wonder how best to organize work with a database from C # code.

I had different approaches for this:

  • Each object has the methods "Save", "Update" and "Delete", in which all the logic is implemented.
  • There was some static class that has the static methods Get, GetList, Update - almost the same method as the previous one, but the database logic was extracted from the data domain class.

Now I think it will be great to have some non-static classes for each of the datadomain classes that I need to store somewhere that the storage will do.

What is the best way to do this? Are there any good libraries that provide a good API for storing objects?

+4
source share
4 answers

Use Map Object / Relation Mapper (ORM). My personal favorite is nhibernate. Use the Entity Framework if you want a Microsoft product.

ORM typically implements UnitOfWork and Repository , which makes it easier for you to process database operations and adhere to the principle of single responsibility.

You also mentioned singles. I would avoid them if possible. Have you tried the unit test class that uses single points? This is not possible if the singleton is not a proxy for the actual implementation. The easiest way to remove singleons is to invert dependencies using dependecy injection . There are several containers.

+5
source

The recommended way to work with databases these days is ORM .

Check out nHibernate (a community project) and Entity Framework (Courtesy of Microsoft) for some of the most popular options for .NET, although there are many more.

These are libraries that give you all the access to the data you need, with some configuration.

+4
source

The repository template is a very common way to structure your data access logic.

+3
source

Both methods push you to check or dismiss when I work.

Cm:

  • Separation of problems. An object must not deal with loading or saving.

  • Static methods for this mean that you can never have the same class in two different databases.

This is a complex issue that has been resolved over 20 years using things like UnitOfWork templates or repository templates. Tons of projects for this - delete β€œC #” (no, man, the world does not recover around one langauge) and look for objects / relational maps. I remember that I used it 20 years ago with the help of samlltalk and wrote 10 years ago in C #, sometimes .NET developers, with large manipulations of text strings, were up to date.

NHibernate, Entity Framework, hell, even BlToolkit, as my preferred lightweight toolkit these days shows you the right templates.

+1
source

Source: https://habr.com/ru/post/1385726/


All Articles