Junior — Middle
What methods do you use to work with the database?
sobes.tech AI
Answer from AI
In C#, there are several common approaches for working with databases:
- ADO.NET — low-level access to the database via SqlConnection, SqlCommand, SqlDataReader. Allows executing SQL queries directly.
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var command = new SqlCommand("SELECT * FROM Users", connection);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["Name"]);
}
}
}
- Entity Framework (EF) — ORM that allows working with the database through objects and LINQ queries, simplifying code and improving readability.
using (var context = new AppDbContext())
{
var users = context.Users.Where(u => u.IsActive).ToList();
foreach(var user in users)
{
Console.WriteLine(user.Name);
}
}
- Dapper — micro-ORM framework that combines convenience and performance, works on top of ADO.NET.
The choice of method depends on performance requirements, convenience, and project complexity.