
Entity Framework Core Advanced
Raw SQL, stored procedures, transactions, AsNoTracking, AsSplitQuery, query tags, interceptors, performance tuning
1How to execute a raw SQL query to retrieve entities in EF Core?
How to execute a raw SQL query to retrieve entities in EF Core?
Answer
The FromSql() or FromSqlRaw() method allows executing raw SQL queries while returning entities tracked by the DbContext. This is useful for scenarios where LINQ cannot express the query directly, such as calling stored procedures or table-valued functions. Results can then be composed with LINQ to add filters or include relationships.
2What is the difference between FromSqlRaw() and ExecuteSqlRaw() in EF Core?
What is the difference between FromSqlRaw() and ExecuteSqlRaw() in EF Core?
Answer
FromSqlRaw() is used to execute SELECT queries that return tracked entities, allowing composition with LINQ. ExecuteSqlRaw() is used to execute non-query commands (INSERT, UPDATE, DELETE) and returns the number of affected rows. FromSqlRaw() applies to a DbSet, while ExecuteSqlRaw() applies to Database. This distinction ensures type safety and model consistency.
3How to call a stored procedure that returns entities in EF Core?
How to call a stored procedure that returns entities in EF Core?
Answer
Use FromSqlRaw() or Database.SqlQuery<T>() to call a stored procedure and map results to entities. It's crucial to add AsEnumerable() after the call to prevent EF Core from attempting to compose on the stored procedure results, which would cause SQL syntax errors. Parameters can be passed using the @p0, @p1 syntax to prevent SQL injection.
What is the role of AsNoTracking() in EF Core?
When to use AsNoTrackingWithIdentityResolution() instead of AsNoTracking()?
+22 interview questions
Other .NET interview topics
C# Basics
LINQ & Delegates
C# Language Essentials
ASP.NET Core Fundamentals
ASP.NET Core Request Lifecycle
Configuration & Settings
Application Lifecycle
Dependency Injection
Entity Framework Core
Minimal APIs
Web API Development
Async in ASP.NET Core
Authentication & Authorization
HttpClient & Networking
JSON Serialization
C# Advanced Features
Clean Architecture
Logging, Monitoring & Observability
Unit Testing & xUnit
Integration Testing
Docker & Containerization
NuGet Package Management
Memory Management & GC
Reactive Programming
Async/await & Patterns
.NET Design Patterns
Performance Optimization
Security & Best Practices
SignalR & Real-time
Microservices Architecture
Master .NET for your next interview
Access all questions, flashcards, technical tests, code review exercises and interview simulators.
Start for free