Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to organize work with database [closed]

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

I used to have different approaches for that:

  1. Each object has Save, Update and Delete methods, which implemented all the logic.
  2. 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?

like image 284
Alexander Romanov Avatar asked Dec 13 '22 07:12

Alexander Romanov


2 Answers

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.

like image 194
jgauffin Avatar answered Dec 30 '22 12:12

jgauffin


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.

like image 22
Oded Avatar answered Dec 30 '22 13:12

Oded