Junior — Middle
How do your application and databases interact through ORM, and how is data model management carried out?
sobes.tech AI
Answer from AI
ORM (Object-Relational Mapping) is a technology that allows interaction with a database through objects and classes in an application, hiding the details of SQL queries.
In C#, ORM, such as Entity Framework, works as follows:
- Each database table is mapped to a class (data model).
- Table columns are mapped to class properties.
- ORM automatically generates SQL queries for CRUD operations (create, read, update, delete) based on changes in objects.
Data model management is done through a data context (e.g., DbContext), which tracks the state of objects:
- Added objects are marked as new records for insertion.
- Modified objects are marked for update.
- Deleted objects are marked for deletion.
Example:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
using(var context = new AppDbContext())
{
var product = new Product { Name = "Book", Price = 9.99m };
context.Products.Add(product); // Add a new model
context.SaveChanges(); // Save changes to the database
}
Thus, ORM simplifies working with the database by allowing you to work with objects instead of raw SQL queries.