Showing 30 question(s)

Answer:

Entity Framework Core (EF Core) is a lightweight, open-source, cross-platform Object Relational Mapper (ORM) developed by Microsoft. It allows developers to work with databases using .NET objects instead of writing raw SQL queries.

Code Example:

using var context = new AppDbContext();

var products = context.Products.ToList();

foreach (var product in products)
{
    Console.WriteLine(product.Name);
}

Tags:

Answer:

EF Core reduces boilerplate code, provides LINQ support, supports migrations, change tracking, lazy/eager loading, cross-platform development, and works with multiple database providers.

Code Example:

// Query using LINQ
var employees = context.Employees
                       .Where(e => e.Salary > 50000)
                       .ToList();

Tags:

Answer:

DbContext is the primary class responsible for interacting with the database. It manages entity objects, tracks changes, executes queries, and saves data.

Code Example:

public class AppDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }
}

Tags:

Answer:

A DbSet represents a table in the database. It is used to query and save instances of a given entity type.

Code Example:

public class AppDbContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
}

var customers = context.Customers.ToList();

Tags:

Answer:

An entity is a C# class that maps to a database table. Each instance of the class represents a row in that table.

Code Example:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
}

Tags:

Answer:

EF Core can be installed using the .NET CLI or NuGet Package Manager. The provider package depends on the database being used.

Code Example:

dotnet add package Microsoft.EntityFrameworkCore

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

dotnet add package Microsoft.EntityFrameworkCore.Tools

Tags:

Answer:

Configure the DbContext inside Program.cs or Startup.cs using dependency injection and provide the SQL Server connection string.

Code Example:

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")));

Tags:

Answer:

Create an entity object, add it to the DbSet, and call SaveChanges() to persist it to the database.

Code Example:

var product = new Product
{
    Name = "Laptop",
    Price = 65000
};

context.Products.Add(product);
context.SaveChanges();

Tags:

Answer:

Use LINQ queries on DbSet to retrieve one or multiple records from the database.

Code Example:

var products = context.Products.ToList();

var product = context.Products
                     .FirstOrDefault(p => p.Id == 1);

Tags:

Answer:

Retrieve the entity, modify its properties, and call SaveChanges(). EF Core automatically tracks changes and generates the appropriate UPDATE statement.

Code Example:

var product = context.Products.Find(1);

if (product != null)
{
    product.Price = 70000;
    context.SaveChanges();
}

Tags:

Answer:

Retrieve the entity, remove it using the Remove() method, and call SaveChanges() to delete it from the database.

Code Example:

var product = context.Products.Find(1);

if (product != null)
{
    context.Products.Remove(product);
    context.SaveChanges();
}

Tags:

Answer:

Migrations are used to keep the database schema synchronized with your entity models. They generate SQL scripts based on model changes.

Code Example:

dotnet ef migrations add InitialCreate

dotnet ef database update

Tags:

Answer:

Use the EF Core CLI or Package Manager Console to generate a migration whenever your model changes.

Code Example:

dotnet ef migrations add AddProductTable

dotnet ef migrations list

Tags:

Answer:

Apply the migration using the database update command, which executes the generated SQL against the target database.

Code Example:

dotnet ef database update

# Apply a specific migration
dotnet ef database update InitialCreate

Tags:

Answer:

EnsureCreated() creates the database directly without using migrations and is suitable for testing. Migrations are recommended for production because they maintain schema history.

Code Example:

using var context = new AppDbContext();

context.Database.EnsureCreated();

// Recommended for production:
// dotnet ef migrations add InitialCreate

Tags:

Answer:

LINQ (Language Integrated Query) allows developers to query the database using strongly typed C# expressions instead of raw SQL.

Code Example:

var products = context.Products
    .Where(p => p.Price > 500)
    .OrderBy(p => p.Name)
    .ToList();

Tags:

Answer:

Use the Where() method to filter records based on one or more conditions.

Code Example:

var employees = context.Employees
    .Where(e => e.Department == "IT")
    .ToList();

Tags:

Answer:

Use OrderBy(), OrderByDescending(), ThenBy(), and ThenByDescending() to sort query results.

Code Example:

var products = context.Products
    .OrderBy(p => p.Name)
    .ThenByDescending(p => p.Price)
    .ToList();

Tags:

Answer:

Use First(), FirstOrDefault(), Single(), or SingleOrDefault() depending on whether you expect one or multiple matching records.

Code Example:

var employee = context.Employees
    .FirstOrDefault(e => e.Id == 10);

if (employee != null)
{
    Console.WriteLine(employee.Name);
}

Tags:

Answer:

FirstOrDefault() returns the first matching record or null if none exists. SingleOrDefault() expects exactly one matching record and throws an exception if multiple records are found.

Code Example:

var first = context.Products
    .FirstOrDefault(p => p.Category == "Laptop");

var single = context.Products
    .SingleOrDefault(p => p.Id == 1);

Tags:

Answer:

Relationships define how entities are connected in the database. EF Core supports One-to-One, One-to-Many, and Many-to-Many relationships.

Code Example:

public class Customer
{
    public int Id { get; set; }
    public List<Order> Orders { get; set; } = new();
}

public class Order
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
    public Customer Customer { get; set; } = null!;
}

Tags:

Answer:

Eager loading loads related entities immediately using Include(). Lazy loading loads related data only when it is accessed, requiring lazy loading proxies.

Code Example:

var orders = context.Orders
    .Include(o => o.Customer)
    .ToList();

Tags:

Answer:

Explicit loading allows related entities to be loaded manually when required instead of automatically.

Code Example:

var customer = context.Customers.Find(1);

context.Entry(customer!)
       .Collection(c => c.Orders)
       .Load();

Tags:

Answer:

Use HasOne(), WithMany(), and HasForeignKey() inside OnModelCreating() to configure relationships.

Code Example:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>()
        .HasOne(o => o.Customer)
        .WithMany(c => c.Orders)
        .HasForeignKey(o => o.CustomerId);
}

Tags:

Answer:

Starting with EF Core 5, many-to-many relationships can be configured without creating an explicit join entity.

Code Example:

public class Student
{
    public ICollection<Course> Courses { get; set; } = new List<Course>();
}

public class Course
{
    public ICollection<Student> Students { get; set; } = new List<Student>();
}

Tags:

Answer:

EF Core automatically tracks changes made to entities so that only modified properties are updated when SaveChanges() is called.

Code Example:

var product = context.Products.Find(1);

product!.Price = 999;

context.SaveChanges();

Tags:

Answer:

Use AsNoTracking() when querying read-only data to improve performance.

Code Example:

var products = context.Products
    .AsNoTracking()
    .ToList();

Tags:

Answer:

Use AsNoTracking(), retrieve only required columns with Select(), avoid unnecessary Include(), implement pagination, and use compiled queries when appropriate.

Code Example:

var products = context.Products
    .Select(p => new
    {
        p.Id,
        p.Name
    })
    .ToList();

Tags:

Answer:

Use Skip() and Take() methods to retrieve only the required page of records.

Code Example:

int page = 2;
int pageSize = 10;

var products = context.Products
    .OrderBy(p => p.Id)
    .Skip((page - 1) * pageSize)
    .Take(pageSize)
    .ToList();

Tags:

Answer:

Use dependency injection for DbContext, use AsNoTracking() for read-only queries, avoid loading unnecessary data, use migrations, prefer async methods, dispose DbContext properly, and use indexes for frequently queried columns.

Code Example:

// Async query
var products = await context.Products
    .AsNoTracking()
    .ToListAsync();

// Save asynchronously
await context.SaveChangesAsync();

Tags: