Interview Q&A

Technical interview questions with detailed answers—organized by course, like Dot Net Tutorials interview sections. Original content for Toolliyo Academy.

Popular tracks

Entity Framework Core Entity Framework Core Tutorial · EF Core

Entity Framework Core (EF Core) is a modern, lightweight, cross-platform, open-source

ORM (Object-Relational Mapper) for .NET. It allows developers to interact with databases

using C# objects rather than SQL queries.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Feature EF6 EF Core

Platform .NET Framework only Cross-platform (.NET Core)

Performance Slower Faster and more optimized

LINQ support Limited Enhanced

Change

tracking

Basic More efficient

Migrations Available Improved and CLI-friendly

Extensibility Limited Highly extensible

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How does EF Core

implement it?

ORM is a technique that maps objects in code to relational database tables. EF Core

implements ORM by mapping .NET classes (entities) to database tables using DbContext,

DbSet, and conventions or Fluent API.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

What responsibilities does it have?

DbContext is the primary class for interacting with the database in EF Core. It:

  • Manages database connections
  • Tracks changes to entities
  • Provides methods for querying and saving data
  • Configures models and relationships
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How does it map to database tables?

DbSet<T> represents a collection of entities of type T in the context. Each DbSet maps to a

table in the database, where T is the type of the entity.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Entities are .NET classes that represent database tables. Each property in the entity maps to

a column. EF Core uses conventions or Fluent API to configure the mappings.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

POCO (Plain Old CLR Object) is a simple class without any dependency on EF Core or any

base class. EF Core uses POCOs as entities for data modeling.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Navigation properties allow navigation from one entity to related entities. They define

relationships (one-to-one, one-to-many, many-to-many).

Example:

public class Order

public int Id { get; set; }

public Customer Customer { get; set; } // Navigation property

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Scalar: Simple types like int, string, DateTime
  • Complex: Nested objects mapped to multiple columns (Value objects)
  • Shadow: Properties not defined in the .NET class but tracked by EF Core
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

What is “LINQ to Entities”?

  • LINQ (Language Integrated Query) lets you query collections using C# syntax.
  • LINQ to Entities is LINQ querying against the EF Core model, translated to SQL and

executed in the database.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

// Create

context.Users.Add(new User { Name = "John" });

context.SaveChanges();

// Read

var user = context.Users.FirstOrDefault(u => u.Id == 1);

// Update

user.Name = "Jane";

context.SaveChanges();

// Delete

context.Users.Remove(user);

context.SaveChanges();

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Productivity via abstraction from SQL
  • Cross-platform support
  • Strongly-typed LINQ queries
  • Migration support
  • Tracks changes automatically
  • Works well with dependency injection
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • May generate inefficient SQL for complex queries
  • Learning curve for advanced features
  • Less control over fine-tuned SQL performance
  • Not ideal for high-performance bulk operations

Entity Framework Core – Schema Design &

Migrations Interview Questions

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Advantages and when to use it

Code First is an EF Core approach where you define your database schema using C#

classes, and EF Core generates the database from your code.

✅ Advantages:

  • Full control via C# code (POCOs)
  • Easily version-controlled
  • Supports migrations to handle schema evolution
  • Works well with Domain-Driven Design

📌 When to use:

When you're starting a new project or prefer designing schema in code.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Use‑cases and pros and cons

Database First involves generating C# entity classes and a DbContext from an existing

database.

✅ Pros:

  • Quick start if the DB already exists
  • Ensures model aligns with legacy databases

❌ Cons:

  • Harder to version control
  • Schema changes must be manually re-scaffolded

📌 When to use:

For integrating with existing databases or legacy systems.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Is it used in EF Core?

Model First allows creating a database model using a designer (EDMX file), then generating

both the database and code from that model.

⚠ EF Core does not support Model First. This approach was available in EF6 with Visual

Studio tooling.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Use the CLI or Package Manager Console:

dotnet ef dbcontext scaffold "YourConnectionString"

Microsoft.EntityFrameworkCore.SqlServer -o Models

Scaffold-DbContext "YourConnectionString"

Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

✅ It generates:

  • Entity classes
  • DbContext class
  • Mappings based on database schema
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

EF Core uses migrations to track and apply schema changes:

  • You modify your C# models.
  • Use Add-Migration to create a migration class.
  • Use Update-Database to apply the changes to the DB.

EF Core compares the model to the current schema to generate SQL.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

🧩 Data Annotations (in the entity class):

[Table("Users")]

public class User

[Key]

public int Id { get; set; }

[Column("UserName")]

public string Name { get; set; }

🧠 Fluent API (in OnModelCreating):

modelBuilder.Entity<User>()

.ToTable("Users")

.HasKey(u => u.Id);

modelBuilder.Entity<User>()

.Property(u => u.Name)

.HasColumnName("UserName");

📌 Fluent API is more powerful and flexible, preferred for complex configurations.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How are they used in Code First?

Migrations in EF Core are a way to:

  • Track schema changes over time
  • Apply those changes to the database

📦 Basic commands:

  • Add-Migration MigrationName
  • Update-Database
  • Remove-Migration
  • Script-Migration

🔄 Migrations are classes containing Up() and Down() methods (for applying and reverting

changes).

📌 They are essential for schema versioning in Code First.

Entity Framework Core – Migrations

Interview Questions

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

(e.g. Add-Migration)

Use one of the following commands:

.NET CLI:

dotnet ef migrations add MigrationName

Package Manager Console:

Add-Migration MigrationName

This creates a migration file with Up() and Down() methods, and a snapshot of the current

model.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

(e.g. Update-Database)

Apply the migration to your database using:

.NET CLI:

dotnet ef database update

Package Manager Console:

Update-Database

EF Core translates your model changes into SQL and executes them against the database.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • A migration snapshot is a C# file (e.g., ModelSnapshot.cs) automatically created

by EF Core.

  • It represents the current model state.
  • EF uses it to compare changes in future migrations.
  • Located in the Migrations folder, named like

[YourDbContext]ModelSnapshot.cs.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

To remove the last migration before applying it:

dotnet ef migrations remove

To rollback the database to a previous migration:

dotnet ef database update MigrationName

To rollback all migrations:

dotnet ef database update 0

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How to generate SQL scripts for

migrations?

Generate SQL script using:

dotnet ef migrations script

To script a specific range:

dotnet ef migrations script FromMigration ToMigration

These scripts are useful for deploying to production environments or executing via CI/CD

pipelines.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Use the HasData() method in OnModelCreating():

modelBuilder.Entity<User>().HasData(

new User { Id = 1, Name = "Admin" }

  • Data is inserted automatically during Update-Database.
  • Changes to seed data require a new migration.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Best practices:

  • Communicate and coordinate migration changes.
  • Always pull and apply the latest migrations before adding a new one.
  • If conflicts arise:
  • Resolve merge conflicts in migration files manually.
  • Rebuild ModelSnapshot as needed.
  • Consider squashing or reorganizing migrations.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Generate SQL script from tested migrations.
  • Manually review and apply via DBA or DevOps tools.

Use EF Core tools in CI/CD (e.g., GitHub Actions, Azure DevOps):

dotnet ef database update --no-build

  • Always backup the database before applying migrations in production.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Scaffolded migrations are the automatically generated classes that contain Up() and

Down() methods.

  • They are generated based on model differences.
  • You can manually edit these files to:
  • Add custom SQL
  • Rename columns
  • Seed data, etc.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

You can manually edit migration files after scaffolding:

protected override void Up(MigrationBuilder migrationBuilder)

migrationBuilder.Sql("UPDATE Users SET IsActive = 1 WHERE

IsActive IS NULL");

  • Add indexes, constraints, stored procedures.
  • Use raw SQL or Fluent API.
  • Be cautious to maintain idempotency and correctness.

Entity Framework Core – Change

Tracking & Concurrency

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Change tracking is the process by which EF Core keeps track of changes made to entities

after they are loaded from the database. This allows EF Core to generate the correct SQL

INSERT, UPDATE, or DELETE statements when SaveChanges() is called.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

EF Core uses these EntityState values:

State Description

Added New entity to be inserted into the database

Modified Entity has been changed and will be updated

Deleted Entity will be deleted from the database

Detached Entity is not tracked by the context

Unchange

No changes have been made since it was

loaded

You can check/set the state via:

context.Entry(entity).State = EntityState.Modified;

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

EF Core tracks changes via:

  • Snapshot change tracking: EF stores a snapshot of original values when entities

are loaded, and compares them before saving.

  • Notifications: If your entities implement INotifyPropertyChanged, EF can track

changes immediately.

EF compares the current values to the original snapshot during SaveChanges().

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Tracked queries: EF Core tracks entities returned from the query. Changes to them

are monitored and persisted.

  • Untracked queries: EF does not monitor the returned entities. Faster, read-only

access.

Tracked (default):

var user = context.Users.FirstOrDefault();

Untracked:

var user = context.Users.AsNoTracking().FirstOrDefault();

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

When to use it?

.AsNoTracking() tells EF Core not to track entities in the returned query.

✅ Use when:

  • Read-only operations
  • Improving performance for large queries
  • Preventing memory overhead of tracking

Example:

var users = context.Users.AsNoTracking().ToList();

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

You can disable tracking by default for a specific DbContext using:

optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTrac

king);

Or per-query using .AsNoTracking().

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Use the Entry() method:

context.Entry(entity).State = EntityState.Modified;

context.Entry(entity).State = EntityState.Detached;

This is helpful when:

  • You’re updating data without reloading it
  • Working with disconnected scenarios (e.g., APIs)
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

What is optimistic concurrency vs

pessimistic concurrency?

  • Optimistic concurrency: Assumes that conflicts are rare. EF checks for changes

before saving using concurrency tokens.

  • Pessimistic concurrency: Locks records in the DB to prevent other updates (not

supported out-of-the-box in EF Core).

EF Core supports optimistic concurrency using [ConcurrencyCheck] or

[Timestamp].

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

A concurrency token is a property used to detect concurrency conflicts.

Example with [Timestamp]:

[Timestamp]

public byte[] RowVersion { get; set; }

  • EF Core includes this column in the WHERE clause of updates.
  • If the row has changed since it was loaded, EF will throw a

DbUpdateConcurrencyException.

Entity Framework Core – Relationships

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

EF Core supports the standard types of relationships:

  • One-to-One (1:1) – One entity has one related entity.
  • One-to-Many (1:N) – One entity relates to many others.
  • Many-to-Many (M:N) – Many entities relate to many others.

Each of these can be configured in EF Core using navigation properties and Fluent API or

Data Annotations.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Example using Fluent API:

modelBuilder.Entity<User>()

.HasOne(u => u.Profile)

.WithOne(p => p.User)

.HasForeignKey<Profile>(p => p.UserId);

Or with data annotations:

public class Profile

[Key, ForeignKey("User")]

public int UserId { get; set; }

public User User { get; set; }

  • Requires a unique foreign key.
  • EF assumes optional by default unless marked as required.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Fluent API:

modelBuilder.Entity<Blog>()

.HasMany(b => b.Posts)

.WithOne(p => p.Blog)

.HasForeignKey(p => p.BlogId);

Data annotations:

public class Post

public int BlogId { get; set; }

[ForeignKey("BlogId")]

public Blog Blog { get; set; }

  • A foreign key exists in the many-side entity (Post).
  • EF infers this relationship from navigation + FK.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

In EF Core 5.0+, you can define many-to-many relationships without an explicit join entity:

public class Student

public ICollection<Course> Courses { get; set; }

public class Course

public ICollection<Student> Students { get; set; }

EF will automatically create a join table CourseStudent behind the scenes.

If you want to customize the join table, define a join entity explicitly.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How to represent them in EF

Core?

A join table maps a many-to-many relationship. In EF Core:

✅ Auto-created (EF Core 5+):

If you define many-to-many with ICollection<T>, EF creates the join table.

🛠 Manual (custom join entity):

public class StudentCourse

public int StudentId { get; set; }

public Student Student { get; set; }

public int CourseId { get; set; }

public Course Course { get; set; }

And configure with Fluent API.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How to define them via

annotations & Fluent API?

  • Primary Key (PK): Unique identifier of a record.
  • Foreign Key (FK): A field that references a PK in another table.

Data Annotations:

[Key]

public int Id { get; set; }

[ForeignKey("Blog")]

public int BlogId { get; set; }

Fluent API:

modelBuilder.Entity<Post>()

.HasKey(p => p.Id);

modelBuilder.Entity<Post>()

.HasOne(p => p.Blog)

.WithMany(b => b.Posts)

.HasForeignKey(p => p.BlogId);

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How to define composite keys in EF Core?

A composite key is a primary key made of multiple columns.

EF Core does not support composite keys via data annotations, so you must use Fluent

API:

modelBuilder.Entity<OrderDetail>()

.HasKey(od => new { od.OrderId, od.ProductId });

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Cascade delete ensures that related entities are deleted when the parent entity is deleted.

Configure with Fluent API:

modelBuilder.Entity<Blog>()

.HasMany(b => b.Posts)

.WithOne(p => p.Blog)

.OnDelete(DeleteBehavior.Cascade);

Delete behaviors:

  • Cascade
  • Restrict
  • SetNull
  • NoAction

EF Core defaults to Cascade for required relationships.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

A shadow property is a property not defined in the .NET class but exists in the EF model.

Example:

modelBuilder.Entity<Post>()

.HasOne<Blog>()

.WithMany()

.HasForeignKey("BlogId"); // BlogId is a shadow FK if not

defined in class

EF tracks it internally but you can't access it in C# code directly.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

In Fluent API:

  • Required:

.HasRequired(p => p.Blog)

  • Optional:

.HasOne(p => p.Blog)

.WithMany()

.IsRequired(false);

EF infers:

  • Reference type (e.g., Blog) → optional by default
  • Non-nullable value type FK (e.g., int BlogId) → required

Entity Framework Core – Lazy vs

Eager vs Explicit Loading

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How is .Include() / .ThenInclude()

used?

Eager loading loads related data as part of the initial query, reducing round-trips to the

database.

✅ Use .Include() to load related entities:

var blogs = context.Blogs

.Include(b => b.Posts)

.ToList();

Use .ThenInclude() for deeper nesting:

context.Blogs

.Include(b => b.Posts)

.ThenInclude(p => p.Comments);

Eager loading prevents lazy load performance issues and the N+1 problem.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How to enable lazy loading in EF Core? What

are proxies?

Lazy loading delays the loading of related data until it's accessed for the first time.

EF Core requires proxies for lazy loading:

Install NuGet:

Microsoft.EntityFrameworkCore.Proxies

Enable in OnConfiguring or AddDbContext:

options.UseLazyLoadingProxies();

Mark navigation properties as virtual:

public virtual ICollection<Post> Posts { get; set; }

EF creates runtime proxies to override navigation properties and load them when

accessed.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

When & how to use it?

Explicit loading means loading related data manually, after the main entity is loaded.

Use when:

  • You need full control over what and when to load
  • You don’t want automatic lazy loading

Example:

var blog = context.Blogs.First();

context.Entry(blog)

.Collection(b => b.Posts)

.Load();

context.Entry(blog)

.Reference(b => b.Owner)

.Load();

✅ Use .Reference().Load() for single navigation

✅ Use .Collection().Load() for collections

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How can lazy loading lead to it?

The N+1 problem occurs when:

  • 1 query loads N parent entities
  • N additional queries load related entities (1 per parent)

Example (lazy loading):

foreach (var blog in context.Blogs)

Console.WriteLine(blog.Owner.Name); // triggers a query for each

blog

This causes N+1 queries, which can hurt performance significantly.

✅ Solution: Use eager loading with .Include() to fetch everything in one query.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Loading

Type

Pros Cons

Eager Fewer queries, good for large data

sets

Loads everything even if not used

Lazy Loads only when needed Risk of N+1 queries, more

round-trips

Explicit Fine-grained control More code complexity

✅ Eager is best for performance when you know you'll need related data.

❌ Lazy can hurt performance unless used carefully (e.g., in UI apps).

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How?

Yes.

You can disable lazy loading globally:

options.UseLazyLoadingProxies(false);

Or don't install the proxy package at all.

You can also disable it for specific navigation properties by not making them virtual.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

By default, EF Core uses no automatic loading — it doesn’t lazy-load or eager-load

relationships unless you:

  • Use .Include() for eager loading
  • Enable lazy loading proxies
  • Use .Load() for explicit loading

This default avoids unintended queries and promotes performance control.

EF Core LINQ Queries & Querying

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

What limitations are there?

  • EF Core translates LINQ queries into SQL using expression trees.
  • Only supported LINQ operators and expressions can be translated.
  • Limitations:
  • Certain C# methods or complex expressions cannot be translated and

cause runtime exceptions.

  • Client-side evaluation may occur, which can hurt performance.
  • Use .AsEnumerable() to switch to client-side processing intentionally.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • IQueryable<T>:
  • Represents a query against the data source.
  • Query is translated to SQL and executed on the database.
  • Supports deferred execution.
  • IEnumerable<T>:
  • Represents an in-memory collection.
  • LINQ operators execute in memory.
  • Usually results after the query has executed and data is loaded.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Inner join example:

var query = from c in context.Customers

join o in context.Orders on c.Id equals o.CustomerId

select new { c.Name, o.OrderDate };

  • Left join (using DefaultIfEmpty()):

var query = from c in context.Customers

join o in context.Orders on c.Id equals o.CustomerId

into orders

from o in orders.DefaultIfEmpty()

select new { c.Name, OrderDate = o != null ? o.OrderDate

: (DateTime?)null };

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

var groupedData = context.Orders

.GroupBy(o => o.CustomerId)

.Select(g => new

CustomerId = g.Key,

TotalOrders = g.Count(),

TotalAmount = g.Sum(o => o.Amount),

MaxAmount = g.Max(o => o.Amount),

MinAmount = g.Min(o => o.Amount)

});

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Filtering:

var filtered = context.Products.Where(p => p.Price > 100);

  • Ordering:

var ordered = context.Products

.OrderBy(p => p.Category)

.ThenByDescending(p => p.Price);

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Projection transforms entities into custom shapes, e.g., DTOs.

var projected = context.Products

.Select(p => new { p.Name, p.Price });

  • Useful for:
  • Reducing data load.
  • Returning only needed fields.
  • Mapping to custom types.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • First(): Returns the first element, throws if none found.
  • FirstOrDefault(): Returns first element or default (null) if none.
  • Single(): Returns the single element, throws if zero or more than one.
  • SingleOrDefault(): Returns the single element or default if none; throws if more

than one.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

(Skip, Take)

  • Use .Skip() and .Take() for pagination:

var page2 = context.Products

.OrderBy(p => p.Id)

.Skip(10) // Skip first 10

.Take(10) // Take next 10

.ToList();

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

(FromSqlRaw, etc.)

  • Use FromSqlRaw() or FromSqlInterpolated():

var products = context.Products

.FromSqlRaw("SELECT * FROM Products WHERE Price > {0}", 100)

.ToList();

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Stored procedures can be called via raw SQL or FromSqlRaw:

var orders = context.Orders

.FromSqlRaw("EXEC GetOrdersByCustomer @CustomerId = {0}",

customerId)

.ToList();

  • For non-query SPs, use Database.ExecuteSqlRaw().
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Precompile frequently used queries to improve performance:

private static readonly Func<MyDbContext, int, Product>

_getProductById =

EF.CompileQuery((MyDbContext ctx, int id) =>

ctx.Products.First(p => p.Id == id));

// Usage:

var product = _getProductById(context, 5);

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Enable logging in DbContext options:

optionsBuilder

.UseSqlServer(connectionString)

.LogTo(Console.WriteLine, LogLevel.Information);

  • Or configure logging in ASP.NET Core logging pipeline.

Repository Pattern & Unit of Work

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Why use it with EF Core (pros and

cons)?

  • Repository Pattern abstracts data access logic, exposing CRUD methods to the

application.

  • Pros:
  • Decouples data access logic from business logic.
  • Easier to mock/test.
  • Encapsulates queries in a single place.
  • Cons:
  • EF Core’s DbContext already acts like a repository and unit of work.
  • Can add unnecessary abstraction and boilerplate.
  • May limit EF Core’s powerful querying features.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How does DbContext relate to Unit

of Work?

  • Unit of Work maintains a list of operations to be committed as a single transaction.
  • EF Core’s DbContext implements Unit of Work, tracking changes and coordinating

commits (SaveChanges()).

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

What are the trade-offs?

  • Generic repository provides CRUD for all entity types.
  • Advantages:
  • Reusable and reduces boilerplate.
  • Simple for basic CRUD.
  • Disadvantages:
  • Can become too generic, losing flexibility for complex queries.
  • May leak EF Core specifics or cause over-abstraction.
  • Sometimes custom repositories per aggregate are better.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Sample signature /

interface?

public interface IRepository<T> where T : class

Task<T> GetByIdAsync(int id);

Task<IEnumerable<T>> GetAllAsync();

Task AddAsync(T entity);

void Update(T entity);

void Delete(T entity);

Task SaveChangesAsync();

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

public interface IUnitOfWork : IDisposable

IRepository<Customer> Customers { get; }

IRepository<Order> Orders { get; }

Task<int> CommitAsync();

  • Implementation typically injects a single DbContext instance shared across

repositories.

  • CommitAsync() calls DbContext.SaveChangesAsync().
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Use DbContext transaction or IDbContextTransaction:

using var transaction = await

_context.Database.BeginTransactionAsync();

try

// multiple repository operations

await _unitOfWork.CommitAsync();

await transaction.CommitAsync();

catch

await transaction.RollbackAsync();

throw;

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Mocking DbContext using frameworks like Moq (complex).
  • Use InMemoryDatabase provider from EF Core for integration-like tests.
  • Abstract dependencies and inject mocked interfaces for isolation.

Performance, Best Practices, &

Advanced Features

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Practical use cases.

  • Properties not defined in your CLR classes but tracked by EF Core.
  • Useful for storing metadata like CreatedBy, LastModified, or foreign keys without

cluttering domain models.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

When/why to use it?

  • A filter automatically applied to all queries on an entity.
  • Useful for soft deletes, multi-tenancy (filtering by tenant ID), or data partitioning.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Use .AsNoTracking() for read-only queries.
  • Avoid over-fetching: only select needed columns (Select).
  • Use eager loading wisely (Include).
  • Minimize round trips by batching operations.
  • Use compiled queries for repeated query patterns.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How does EF Core handle batch operations?

  • EF Core batches multiple commands into a single database round trip when

possible.

  • Improves performance by reducing network overhead.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Use pagination (Skip, Take).
  • Use streaming APIs like IAsyncEnumerable<T> with EF Core 5+.
  • Avoid loading all data into memory at once.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • EF Core doesn’t have built-in caching for query results.
  • Use second-level caching libraries (like EFCoreSecondLevelCacheInterceptor).
  • Use application-level caching (MemoryCache, Redis) strategically.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Use FromSqlRaw or ExecuteSqlRaw to execute raw SQL.
  • Map results to entities or DTOs.
  • Use for performance-critical or legacy operations not easily expressed in LINQ.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

SQL Server, PostgreSQL, MySQL —

differences, limitations?

  • Providers abstract database-specific implementations.
  • Each supports different features & SQL dialects.
  • Some features may not be supported on all providers (e.g., some EF Core features

are provider-specific).

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Migrations support may be limited or unavailable.
  • May require manual scripts or provider-specific tooling.
  • Consider NoSQL-specific approaches for schema changes.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Use shadow properties or explicit properties for timestamps.
  • Override SaveChanges() to set audit fields.
  • Use global query filters for soft delete support.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

Implementation strategies in EF Core?

  • Mark entities as deleted without physically removing them.
  • Implemented using a boolean flag and global query filters to exclude “deleted”

records.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • EF Core can track foreign keys without them being defined in your model as

properties.

  • Useful for cleaner domain models.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Configure relationships explicitly.
  • HasOne / WithMany to define navigation properties and cardinality.
  • Offers fine control beyond Data Annotations.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Convert CLR types to database-compatible types and vice versa.
  • Example: storing an enum as a string or encrypted data.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

When to use them?

  • Complex types that don’t have their own identity and lifecycle.
  • Useful for grouping related properties (like Address inside a Customer).
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Private fields in your entity class mapped by EF Core instead of public properties.
  • Useful for encapsulating domain logic and controlling property access.

Transactions, Concurrency, Security

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • EF Core automatically wraps SaveChanges() calls in a transaction.
  • Ensures all changes are committed atomically.
  • For multiple SaveChanges() calls, transactions need manual handling.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

(BeginTransaction, Commit,

Rollback)

  • Use DbContext.Database.BeginTransaction() to start a transaction.
  • Call Commit() to save changes or Rollback() to undo.
  • Useful for combining multiple operations that should succeed or fail as a unit.

using var transaction = context.Database.BeginTransaction();

try {

// Perform multiple operations

context.SaveChanges();

transaction.Commit();

} catch {

transaction.Rollback();

throw;

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How to implement it?

  • Assumes conflicts are rare; detects conflicts when saving.
  • Uses concurrency tokens (e.g., timestamp or row version) to detect if data was

changed by another process.

  • EF Core throws DbUpdateConcurrencyException if a conflict occurs.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Properties marked with [Timestamp] or configured as concurrency tokens.
  • Stored in the database as rowversion/timestamp type or other markers.
  • EF Core checks these tokens during updates/deletes to detect concurrent changes.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Catch DbUpdateConcurrencyException.
  • Reload conflicting entity from database or merge changes.
  • Retry operation or notify the user of conflict.
  • Implement custom conflict resolution logic as needed.

Testing, Deployment, Tools

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Unit Tests: Focus on logic without actual database. Use mocks or in-memory

databases to isolate tests.

  • Integration Tests: Use real database (or test instance) to validate EF Core behavior,

migrations, and data persistence.

  • Tests cover CRUD operations, queries, and business logic using EF Core.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • EF Core InMemory provider: Lightweight, fast, but doesn’t mimic relational

database behavior exactly (no relational constraints, transactions).

  • Other options: SQLite in-memory mode (better relational simulation).
  • Use InMemory for unit tests; SQLite for more realistic integration testing.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Mock DbContext using libraries like Moq, but it can be complex due to EF internals.
  • Better to abstract data access via repositories/interfaces, then mock those interfaces

in tests.

  • Alternatively, use in-memory or SQLite database for integration tests instead of

mocking DbContext.

Miscellaneous / Scenario / Trick

Questions

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Use separate migration folders per DbContext via the -Context option in

Add-Migration.

  • Maintain separate migration history tables using MigrationsHistoryTable

method.

  • Apply migrations independently for each DbContext.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Configure DbContext in Startup or Program to select provider based on

environment variables or config files.

  • Use DI to inject correct connection strings and providers.
  • Can use conditional compilation or environment-based settings.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Use migrations scripts with data transformation carefully.
  • Apply backward-compatible schema changes first (add columns instead of drop).
  • Use feature flags or phased deployment.
  • Run migrations during maintenance windows or use rolling updates.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Use IHostingEnvironment or config flags inside the DbContext

OnModelCreating or after migration.

  • Separate seed classes or methods per environment.
  • Use EF Core’s HasData method or custom seed logic at runtime.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Use [JsonIgnore] or ReferenceLoopHandling.Ignore in JSON serialization.
  • Use DTOs without circular refs for API responses.
  • Carefully design navigation properties to avoid cycles or use explicit loading.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Define navigation property and foreign key for self-reference.
  • Use Fluent API: .HasOne(e => e.Manager).WithMany(e =>

e.Subordinates).

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Use FromSqlRaw or FromSqlInterpolated for stored procedures and views.
  • Map views as query types or entities without keys (read-only).
  • For insert/update via SP, call them directly from DbContext.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Throws InvalidOperationException or returns null since no tracking or lazy loading.
  • Need to attach entity or explicitly load navigation properties.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Use context.Entry(entity).State = EntityState.Detached.
  • Useful to avoid tracking or to simulate detached state.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Attach entity, then set only modified properties as Modified.
  • Use context.Entry(entity).Property(p =>

p.PropertyName).IsModified = true.

  • Useful for PATCH operations.
Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

  • Use libraries like EFCore.BulkExtensions, Z.EntityFramework.Extensions.
  • These provide optimized bulk operations, bypassing EF change tracking for

performance.

Permalink

Entity Framework Core Entity Framework Core Tutorial · EF Core

How does the dynamic proxy work under the hood?

  • EF Core creates a dynamic proxy subclass of your entity at runtime.
  • Proxy overrides virtual navigation properties to load related data on-demand.
  • Requires navigation properties to be virtual and package

Microsoft.EntityFrameworkCore.Proxies.

  • Proxy intercepts access and triggers loading when property is accessed.
Permalink