Junior — Middle
Explain the principle of how ORM systems work and how they relate to object-oriented programming?
sobes.tech AI
Answer from AI
ORM (Object-Relational Mapping) is a technology that allows working with a database through objects in an object-oriented programming language. It automatically converts data from a relational model (tables, rows, columns) into objects and vice versa.
Relation to OOP:
- Each database table corresponds to a class.
- Each row of the table is an instance of the class (an object).
- The columns of the table are properties of the object.
This allows developers to work with data as if they were regular objects, without writing SQL queries manually, but using class methods and properties.
Example in C# using Entity Framework:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
using(var context = new AppDbContext())
{
var user = new User { Name = "Ivan" };
context.Users.Add(user);
context.SaveChanges();
}
Here, the User class corresponds to the Users table, and the ORM will generate the SQL query to insert data.