└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # Top 100 Entity Framework Interview Questions in 2025 2 | 3 |
4 |

5 | 6 | web-and-mobile-development 7 | 8 |

9 | 10 | #### You can also find all 100 answers here 👉 [Devinterview.io - Entity Framework](https://devinterview.io/questions/web-and-mobile-development/entity-framework-interview-questions) 11 | 12 |
13 | 14 | ## 1. What is an ORM and how does _Entity Framework_ function as one? 15 | 16 | **Object-Relational Mapping** (ORM) bridges the gap between object-oriented code and relational databases. 17 | 18 | Key components include: 19 | 20 | - **Model**: Defines the data structure. 21 | - **Context**: Acts as an in-memory database, allowing CRUD operations. 22 | - **Mappings**: Specifies relationships between classes and database tables. 23 | 24 | ### Working of the Entity Framework 25 | 26 | - **Model First**: Design the model, then generate the database. 27 | - **Database First**: Use an existing database to generate a model. 28 | - **Code First**: Define classes and relationships first, then generate a database. 29 | 30 | ### Core Concepts of EF 31 | 32 | - **DbContext**: Represents a session with the database. 33 | 34 | - **Entity**: An object that you map to a table or a view in the database. 35 | 36 | - **DbSet\**: Represents a table or a view. 37 | 38 | - **Entity State**: Describes the state of an entity in the context. 39 | 40 | - Added 41 | - Modified 42 | - Deleted 43 | - Detached 44 | - Unchanged 45 | 46 | - **Query**: Describes how data is retrieved through LINQ. 47 | 48 | ### Coordination Between Database and Objects 49 | 50 | - **Change Tracking**: Records modifications made to entity objects during their lifecycle. 51 | 52 | - **Relationship Management**: Manages relational data by using techniques like lazy loading, eager loading, and explicit loading. 53 | 54 | - **Transaction Management**: Handles unit of work operations within the database. 55 | 56 | - **Caching**: Maintains an in-memory state of entities for enhanced performance. 57 | 58 | ### Code Example: Entity Framework 59 | 60 | Here is the Csharp code: 61 | 62 | ```csharp 63 | // Define the model 64 | public class Customer { 65 | public int Id { get; set; } 66 | public string Name { get; set; } 67 | public ICollection Orders { get; } = new List(); 68 | } 69 | 70 | public class Order { 71 | public int Id { get; set; } 72 | public decimal Amount { get; set; } 73 | } 74 | 75 | // Define the context 76 | public class MyDbContext : DbContext { 77 | public DbSet Customers { get; set; } 78 | public DbSet Orders { get; set; } 79 | } 80 | 81 | // Usage 82 | using (var context = new MyDbContext()) { 83 | // Insert 84 | var customer = new Customer { Name = "John Doe" }; 85 | context.Customers.Add(customer); 86 | 87 | // Query 88 | var customersWithOrders = context.Customers.Include(c => c.Orders).ToList(); 89 | 90 | // Update 91 | customer.Name = "Jane Doe"; 92 | 93 | // Remove 94 | context.Customers.Remove(customer); 95 | 96 | // Save changes 97 | context.SaveChanges(); 98 | } 99 | ``` 100 |
101 | 102 | ## 2. Can you explain the architecture of _Entity Framework_? 103 | 104 | **Entity Framework** (EF) provides an abstraction layer for developers, allowing them to work with **object-oriented programming** (OOP) constructs for database operations. It's a powerful **Object-Relational Mapping** (ORM) tool that offers a range of features, including querying, change tracking, and more. 105 | 106 | ### Key Components 107 | 108 | - **Context**: Acts as a gatekeeper between your application and the database. It represents a session and holds an **object cache**. 109 | - **Entity**: A plain-old CLR object (POCO), reflective of a database table or view. 110 | - **Storage Model**: Represents the database schema, including tables, relationships, and views. 111 | - **Mapping**: Establishes the relationships between entities and the storage model. 112 | 113 | ### 3 Fundamental Aspects 114 | 115 | - **Model**: Describes the entities, their properties, and relationships. The model is defined using Code-First, Database-First, or Model-First approaches. EF can also infer the model from an existing database. 116 | 117 | - **Database**: Represents the storage where the entity data is persisted. 118 | 119 | - **Data Services**: Provide mechanisms to query and perform CRUD (Create, Read, Update, Delete) operations on entities in the database. 120 | 121 | ### EF Architecture Styles 122 | 123 | #### Code-First 124 | 125 | - **Development Approach**: Begins with the definition of your model classes and relationships, and EF generates the database schema accordingly. 126 | - **Use Case**: Ideal for scenarios where you have an existing database but want to develop and maintain the database schema using C# or VB.NET. 127 | 128 | #### Database-First 129 | 130 | - **Development Approach**: Involves designing the database schema first and then creating the EF model based on the schema. 131 | - **Use Case**: Suited when you need to work with an existing database and want to generate the model classes based on that database. 132 | 133 | #### Model-First 134 | 135 | - **Development Approach**: Implement the model graphically via the EF designer or XML-based EDMX file, and then generate the database schema and model classes. 136 | - **Use Case**: Typically used in legacy applications or for rapid application development where the model is defined first and is then used to generate the database schema and classes. 137 | 138 | #### Hybrid Approaches 139 | 140 | In many real-world applications, the clear distinction between the development approaches might not always hold true. For instance, an application that began with a Database-First approach might over time introduce new features via the Code-First style. This evolution creates a **hybrid** design, combining the strengths of the various approaches. 141 |
142 | 143 | ## 3. What are the main differences between _Entity Framework_ and _LINQ to SQL_? 144 | 145 | **Entity Framework** and **LINQ to SQL** are both Object Relational Mapping (ORM) frameworks designed for .NET applications. 146 | 147 | However, the two differ in various aspects. 148 | 149 | ### Background 150 | 151 | - **Entity Framework**: It was developed by Microsoft as part of the ADO.NET family. It supports visual designers and can generate code from databases and vice-versa. 152 | 153 | - **LINQ to SQL**: While also developed by Microsoft, it's more lightweight compared to EF. It's specifically designed for modeling databases using objects, methods, and LINQ. 154 | 155 | ### Relationship Capabilities 156 | 157 | - **Entity Framework**: It offers better support for complex relationships, including many-to-many relationships. 158 | 159 | - **LINQ to SQL**: It supports basic relationships, but isn't as robust in managing complex ones. 160 | 161 | ### Code and Database Synchronization 162 | 163 | - **Entity Framework**: It features database-first, code-first, and model-first approaches. It can synchronize the code with the database schema. 164 | 165 | - **LINQ to SQL**: It's primarily a database-first approach. Changes to the database must be reflected in the code manually. 166 | 167 | ### Schema Evolution 168 | 169 | - **Entity Framework**: It supports automatic database migration through code-first approaches, making it convenient for evolving schemas. 170 | 171 | - **LINQ to SQL**: It requires manual updates to the model, and these changes need to be explicitly propagated to the database. It does not support automatic migration. 172 | 173 | ### Querying Capabilities 174 | 175 | - **Entity Framework**: Its querying capabilities are broader due to its ability to work with objects outside the database context, like in-memory datasets. 176 | 177 | - **LINQ to SQL**: With a focus on the database, it's optimized for translating LINQ queries directly to SQL, but it's not as versatile as EF. 178 | 179 | ### Performance and Overhead 180 | 181 | - **Entity Framework**: With its superior feature set, it can introduce more overhead, especially in complex scenarios. 182 | 183 | - **LINQ to SQL**: As a more focused and lighter framework, it can sometimes provide better performance in specific use cases. 184 | 185 | ### Data Integrity and Transactions 186 | 187 | - **Entity Framework**: It offers better data integrity management and **transactional support** due to its broader feature set. 188 | 189 | - **LINQ to SQL**: It's not as robust in managing transactions and data integrity. 190 | 191 | ### Customization and Fine-Tuning 192 | 193 | - **Entity Framework**: Given its feature-rich nature, it offers more options for fine-tuning, especially relating to caching, data loading mechanism, etc. 194 | 195 | - **LINQ to SQL**: While potentially providing better performance in simpler scenarios, it offers limited options for fine-tuning and optimization. 196 | 197 | ### Suitable Use Cases 198 | 199 | - **Entity Framework**: It's a comprehensive ORM framework suited for complex enterprise systems, multi-tiered applications, or applications where the database schema evolves frequently. 200 | 201 | - **LINQ to SQL**: Due to its lightweight nature, it's better suited for simple applications or those where extensive ORM features aren't required. 202 |
203 | 204 | ## 4. What is _DbContext_ and how is it used in _EF_? 205 | 206 | **DbContext**, a key part of **Entity Framework**, functions as an intelligent bridge between the application and the database. It encapsulates the database session and acts as a hub where entities are tracked, changes are managed, and datasets are queried and persisted. 207 | 208 | ### Setup and Best Practices 209 | 210 | - **Database Context**: Establish a database connection and provide database operations. 211 | - **Entity Sets**: Represent tables, their records, and relationships. 212 | 213 | ### Key Features 214 | 215 | - **Change Tracking**: Alerts on any modifications to entities. 216 | - **Lazy Loading**: On-demand loading of related entities. 217 | - **Early Loading**: Immediate retrieval of data, including related entities. 218 | 219 | ### Management and Persistence 220 | 221 | - **Inserts** 222 | - **Updates** 223 | - **Deletions** 224 | - **Transactions**: Ensures atomic operations, safeguarded by rollback mechanisms. 225 | 226 | ### Context Lifecycle 227 | 228 | - **Transient**: New instances are used per request. 229 | - **Scoped**: Corresponds to a unit of work or an HTTP request. 230 | - **Singleton**: A single instance shared across the entire application. 231 | 232 | ### Code Example: DbContext 233 | 234 | Here is the C# code: 235 | 236 | ```csharp 237 | using System; 238 | using Microsoft.EntityFrameworkCore; 239 | 240 | public class Product { 241 | public int Id { get; set; } 242 | public string Name { get; set; } 243 | } 244 | 245 | public class StoreContext : DbContext { 246 | public DbSet Products { get; set; } 247 | 248 | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { 249 | optionsBuilder.UseSqlServer("connection string"); 250 | } 251 | } 252 | 253 | // Context usage 254 | public class Program { 255 | static void Main() { 256 | using (var context = new StoreContext()) { 257 | // New product 258 | var newProduct = new Product { Name = "Laptop" }; 259 | context.Products.Add(newProduct); 260 | 261 | // Update existing product 262 | var existingProduct = context.Products.Find(1); 263 | if (existingProduct != null) { 264 | existingProduct.Name = "Desktop"; 265 | } 266 | 267 | // Delete a product 268 | var productToDelete = context.Products.Find(2); 269 | if (productToDelete != null) { 270 | context.Products.Remove(productToDelete); 271 | } 272 | 273 | // Commit changes 274 | context.SaveChanges(); 275 | } 276 | } 277 | } 278 | ``` 279 |
280 | 281 | ## 5. What is the purpose of _DbSet_ in _Entity Framework_? 282 | 283 | **DbSet** in **Entity Framework** acts as a gateway to relational databases, enabling you to interact with database tables using object-oriented programming. 284 | 285 | ### Core Functions 286 | 287 | 1. **Entity Tracking**: DbSet monitors changes made to the entities during their lifespan. Modifications are categorized as Added, Deleted, or Updated, based on which Entity Framework controls how the changes are reflected in the database. 288 | 289 | 2. **LINQ Queries**: You can harness the power of Language-Integrated Query (LINQ) to extract, manipulate, and in some cases, construct new model entities from database tables. DbSet acts as a LINQ query provider. 290 | 291 | 3. **CRUD Operations**: DbSet provides straightforward methods to: insert new entities (**Add**), update their values (**Update**), remove them (**Remove**), retrieve entities by their primary key (**Find**), and also execute bulk operations such as deleting all entities from the table in memory (**RemoveRange**). 292 | 293 | 4. **Data Binding**: It offers data binding capabilities, making it easier to integrate entities seamlessly with UI components in supported platforms like WPF and WinForms. This ensures that changes in UI maps back to the entities and vice versa, and these changes are tracked effortlessly by the DbSet. This aids in handling more extensive workflows with many entities and updates. **However, Data Binding is not supported in the most recent versions of Entity Framework Core**. 294 | 295 | ### Code Example: Working with DbSet 296 | 297 | Here is the C# code: 298 | 299 | ```csharp 300 | public class MyDbContext : DbContext 301 | { 302 | public DbSet Employees { get; set; } 303 | } 304 | 305 | public static void Main() 306 | { 307 | using (var context = new MyDbContext()) 308 | { 309 | // Retrieve an employee by their unique identifier 310 | var employee = context.Employees.Find(1); 311 | 312 | // Update the title of the employee 313 | employee.Title = "Senior Engineer"; 314 | 315 | // Mark the entity as Modified 316 | context.Employees.Update(employee); 317 | 318 | // Save changes to the database 319 | context.SaveChanges(); 320 | 321 | // Delete an employee 322 | var employeeToDelete = context.Employees.Find(2); 323 | context.Employees.Remove(employeeToDelete); 324 | context.SaveChanges(); 325 | 326 | // Query for a specific set of employees 327 | var engineeringEmployees = context.Employees.Where(e => e.Department == "Engineering").ToList(); 328 | } 329 | } 330 | ``` 331 |
332 | 333 | ## 6. Can you describe the concept of _migrations_ in _EF_? 334 | 335 | **Entity Framework** (EF) **Migrations** streamline the management of database schema changes, offering an automated approach to keep the schema in sync with your model. 336 | 337 | ### Why Use Migrations 338 | 339 | - **Schema Evolution**: Migrations facilitate seamless updates to the database schema as the underlying model evolves. 340 | 341 | - **Collaboration**: By keeping schema changes as code, the entire development team can track, review, and apply them using source control management. 342 | 343 | - **Automation**: Migrating databases can be a near-automated task in environments such as build pipelines or during application upgrades. 344 | 345 | - **Reproducibility**: With each schema change being versioned, rollback and forward/backward compatibility becomes clearer and more manageable. 346 | 347 | - **Multistep Migrations**: Complicated updates that involve several smaller changes can be broken down into sequential migrations, ensuring that at each intermediate step, the database remains in a consistent state. 348 | 349 | - **Code Paradigm**: Developers can remain in the code-first perspective, designing models and letting EF take care of the database details. 350 | 351 | ### Key Concepts 352 | 353 | - **Migration**: A script or set of instructions that transforms the database from one state to another. 354 | 355 | - **Migration History Table**: A system table in the database that stores the chronology of applied migrations. This allows EF to determine the current state of the database and what migrations, if any, are pending. 356 | 357 | - **Migration Configuration**: Migrations can be tuned and customized through a dedicated configuration class. 358 | 359 | - **Model Snapshot**: Migrations are backed by a "snapshot" of the model at each evolutionary stage, enabling EF to compare the existing database with the model and generate required scripts. 360 | 361 | ### The Workflow 362 | 363 | Entity Framework organizes the migration workflow into distinct steps: 364 | 365 | 1. **Create Initial Migration**: This step is about establishing the starting point—creating a migration that encompasses the existing model. 366 | 367 | 2. **Code and Model Changes**: Whenever you make changes to your code-first model, you sync these changes using Migrations. This typically involves a few commands provided by your development environment, such as **add-migration** in Visual Studio or **dotnet ef migrations add** via the .NET CLI. 368 | 369 | 3. **Database Update**: Once the migration script is generated, you apply the changes to the database. This is done using **update-database** in Visual Studio, **dotnet ef database update** in the .NET CLI, or programmatically in your code. 370 | 371 | For example, in C#, you would call Context.Database.Migrate() during the database initialization process. 372 | 373 | ### Best Practices 374 | 375 | - **Consistent Naming**: Maintain a unified and meaningful naming convention for your migrations to ensure clarity, especially in team settings. 376 | 377 | - **Continuous Migration**: Invest in a reflexive approach where, as part of the development pipeline, databases are continuously and seamlessly updated. 378 | 379 | - **Source Control**: Migrations are essentially code that should be tracked, versioned, and deployed along with your application code. 380 | 381 | - **Validation**: Before applying a migration, consider running automated tests to ensure systemic stability. 382 | 383 | - **Periodic Cleanup**: Over time, your project may accumulate numerous migrations. Consolidate or remove obsolete ones to keep the codebase manageable. 384 | 385 | ### Code Example: Data Annotations for Migrations 386 | 387 | Here is the C# code: 388 | 389 | ```csharp 390 | public class Customer 391 | { 392 | [Key] // Identifies the primary key of the entity. 393 | public int CustomerId { get; set; } 394 | 395 | [Required] // Specifies that a value is required for the property. 396 | public string Name { get; set; } 397 | } 398 | ``` 399 |
400 | 401 | ## 7. How does _EF_ implement _code-first_, _database-first_, and _model-first_ approaches? 402 | 403 | Let's explore how **Entity Framework (EF)** implements three primary design methodologies: **Code-First**, **Database-First**, and **Model-First**. 404 | 405 | ### Database-First 406 | 407 | In a **Database-First** approach, the data model *initially* resides in an existing database. EF then generates the corresponding model and code. 408 | 409 | #### Process Steps 410 | 411 | 1. **Generate Object Context**: Tools such as `Entity Framework Designer` in Visual Studio or CLI-based `ef` commands build an **Object Context** derived from the database schema. This context forms a bridge between database entities and the application's domain model. 412 | 413 | 2. **Create Entity Classes**: EF creates entity classes corresponding to database tables, along with necessary properties and relationships. These classes map closely to the existing schema. 414 | 415 | 3. **Compile and Use**: Developers integrate the generated classes with their applications and invoke the database via these entities. 416 | 417 | #### Benefits 418 | 419 | - Quick adaptability to existing databases for legacy systems or applications with strict schema requirements. 420 | - Automatic code generation streamlines the development process. 421 | 422 | #### Limitations 423 | 424 | - **Extra Work for Complex Changes**: Efficiently handling complex updates to the database structure can be challenging. 425 | 426 | ### Code-First 427 | 428 | In a **Code-First** approach, developers define the data model using accessible classes. This model acts as the primary resource for schema creation and database persistence. 429 | 430 | #### Process Steps 431 | 432 | 1. **Write POCO Classes**: Developers craft plain, POCO (Plain Old CLR Object) classes representing the business entities of the application. Annotations or a Fluent API configuration guide EF in understanding how these classes map to the database. 433 | 434 | 2. **Create Data Context**: A context class, derived from `DbContext`, serves as an access point to the database and a tracker for entity changes. 435 | 436 | 3. **Refine Model as Necessary**: Refinement of the model is consistent with the application's evolving requirements. Migrations, for instance, allow for the sequential remodeling of the database. 437 | 438 | 4. **Database Generation/Application Launch**: The database schema is either generated or updated when the application runs. This can be achieved using migrations or by explicitly invoking the database initialize method in code. 439 | 440 | #### Benefits 441 | 442 | - **Flexible Model Evolution**: The data model adapts directly to the evolving needs of the application. 443 | - **Coherent Code and Database Schema Maintenance**: Simplified schema management from the codebase, supporting version control and collaborative development. 444 | 445 | #### Limitations 446 | 447 | - **Potential Synchronization Issues**: Developers must ensure that the application's classes and the underlying database schema stay aligned. 448 | 449 | ### Model-First 450 | 451 | In the **Model-First** approach, developers define the conceptual model using a designer tool. This high-level model is refined, and database schema and code are then generated accordingly. 452 | 453 | #### Process Steps 454 | 455 | 1. **Design Conceptual Model**: An EF Designer or Model Builder tool such as Visual Studio's **Entity Data Model Designer** is used to define a conceptual model. This encompasses entities, relationships, and other data-related features. 456 | 457 | 2. **Generate Database from EF Model**: After establishing the conceptual model, configuration tools in Visual Studio or `Entity Data Model Wizard` generate the underlying database schema. 458 | 459 | 3. **Code Generation**: EF also facilitates the automatic creation of classes that mirror the model, using tools like **T4 Templates** or designers. 460 | 461 | #### Benefits 462 | 463 | - **Visual Modeling First**: Offers an intuitive approach for initial model creation, often beneficial for understanding business requirements. 464 | - **Unified Development Environment**: Developers can manage the complete process, from model design to code generation, within a single tool such as Visual Studio. 465 | 466 | #### Limitations 467 | 468 | **Model-Code Mismatch Potential**: Designs may not perfectly match generated code, and manual code changes can impact future model-based code generation. 469 | 470 | The Database-First approach is particularly helpful for legacy databases and was widely used in earlier EF versions. In contrast, Code-First has become a preferred choice for new projects due to its better control over data models and support for model evolution through features like Migrations. Visual Studio's designer is suitable for projects that require rapid visualization, but its use is limited in continuous integration and delivery scenarios. 471 |
472 | 473 | ## 8. What is the role of the _EdmGen_ tool in _EF_? 474 | 475 | The `_EdmGen` tool plays a vital role in **Entity Framework**, especially during design and build phases. 476 | 477 | ### What is \_EdmGen\_? 478 | 479 | The EdmGen tool is a command-line utility that comes with Entity Framework. Its main purpose is to generate storage model from the conceptual model and mapping files. 480 | 481 | ### Key Functions 482 | 483 | - **Generates** three types of files: .csdl (Conceptual Schema Definition Language), .ssdl (Storage Schema Definition Language), and .msl (Mapping Schema Language). These represent the three components of the Entity Data Model (EDM): conceptual model, storage model, and mapping files. 484 | - **Helps** in database-first, code-first, and model-first development paradigms. 485 | 486 | ### Code Example: Running \_EdmGen\_ 487 | 488 | The following command generates .csdl, .ssdl, and .msl files and specifies the output directory: 489 | 490 | ```bash 491 | EdmGen /mode:GenerateArtifact 492 | /outDir:"C:\MyProject" 493 | /nameSpace:MyApp 494 | /project:MyModelProject 495 | /language:CSharp 496 | /connectionString:"metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl; providerName=System.Data.SqlClient;provider connection string='data source=.;initial catalog=MyDatabase;integrated security=True;multipleactiveresultsets=True;App=EntityFramework'" 497 | /entityContainer:MyEntities 498 | ``` 499 | 500 | ### From Command Line to Visual Studio 501 | 502 | Over time, the use of the **EdmGen** tool has diminished, thanks to the enhanced integration of Entity Framework in Visual Studio, especially for database-first and model-first workflows. Visual Studio's "Update Model Wizard" or the package manager console's scaffold commands are commonly used in modern EF-based projects, reducing the direct need for EdmGen. 503 |
504 | 505 | ## 9. Can you describe the _Entity Data Model (EDM)_ in _EF_? 506 | 507 | The **Entity Data Model** (EDM) is a multi-layered, conceptual framework that facilitates data management in Entity Framework. 508 | 509 | ### Core Components 510 | 511 | 1. **Entity Type**: Represents an object or data, such as a person or product. An entity type corresponds to a table in a database. 512 | 513 | Example: 514 | ```C# 515 | public class Product 516 | { 517 | public int ProductID { get; set; } 518 | public string Name { get; set; } 519 | public decimal Price { get; set; } 520 | } 521 | ``` 522 | 523 | 2. **Entity Set**: This is a collection or group of entity instances of a specific entity type. Internally, they map to tables in the database. 524 | 525 | Example: 526 | ```C# 527 | public DbSet Products { get; set; } 528 | ``` 529 | 530 | 3. **Association**: Specifies the relationship between two or more entity types. For instance, in a one-to-many relationship between `Order` and `Product`, an `Order` can have multiple `Products`. 531 | 532 | Example: 533 | ```C# 534 | public class Order 535 | { 536 | [Key] 537 | public int OrderID { get; set; } 538 | public ICollection Products { get; set; } 539 | } 540 | ``` 541 | 542 | 4. **Complex Type**: Represents an object with a composite state, possibly comprising various related entities. It doesn't have a key attribute and cannot exist independently. 543 | 544 | Example: 545 | ```C# 546 | [ComplexType] 547 | public class Address 548 | { 549 | public string Street { get; set; } 550 | public string City { get; set; } 551 | public string ZipCode { get; set; } 552 | } 553 | ``` 554 | 555 | 5. **Association Set**: This corresponds to a group of related entities. It's primarily used for tracking relationships in the database. 556 | 557 | 6. **Function Import**: Maps stored procedures or user-defined functions in the database to corresponding methods in the context. 558 | 559 | 7. **Scalar Property**: Represents simple, individual properties of an entity type. 560 | 561 | 8. **Navigation Property**: Enables navigation from one end of an association to another. 562 | 563 | 9. **Entity Container**: This acts as a container for all the objects used within the model, like entity types, complex types, and entity sets. 564 | 565 | 10. **Inheritance**: Allows for object-oriented concepts such as **inheritance** and **polymorphism** in the model. You can define **base** and **derived** entity types. When you create a hierarchy, EF organizes the entities in a database table to mirror this relationship. 566 | 567 | 11. **Child Entity Type**: When using the TPH strategy, child types come into play. They represent types that inherit from a parent entity type and exist in a TPH configuration. 568 | 569 | ### Database-First Design 570 | 571 | The EDM provides for **Database-First** design, where the EDM and entities are generated from an existing database schema. This method offers a parallel advantage where when the database schema undergoes changes, the modifications are mirrored in the model. 572 | 573 | ### Code-First Approach 574 | 575 | With the Code-First approach, which is commonly known and preferred by developers because of the flexibility and ease of sharing with the teams, the EDM is derived from the code representation of the data model. Developers write classes to represent the model and establish relationships within them, and EF generates the database based on these classes. 576 | 577 | ### Model-First Strategy 578 | 579 | The **Model-First** strategy allows developers to create the EDM graphically using designer tools such as Visual Studio's EDM Designer. This method is especially favored where intricate models are in play. 580 | 581 | **What's noteworthy** is EDM's capability to cater to multiple storage schemas. Whether the source is a relevant database, an XML document, or various data sources, **EDM** is versatile and adaptable. 582 |
583 | 584 | ## 10. How does _lazy loading_ work in _EF_? 585 | 586 | **Lazy loading** allows related objects to be fetched from the database only when they are accessed. This reduces the initial data load, making the system more efficient. 587 | 588 | ### Key Components 589 | 590 | - **Proxy Generation**: When a navigation property is virtual, Entity Framework generates a dynamic proxy at runtime. 591 | 592 | - **Interception Mechanism**: Access to the navigation property triggers a database query through a proxy instance. The process is monitored by EF to maintain data consistency. 593 | 594 | - **Underlying Context Connection**: The context maintains a virtual link to related entities. Actual data fetching occurs once there's a navigation property access for the first time within a context session. 595 | 596 | ### Performance Considerations 597 | 598 | While lazy loading can enhance efficiency, it may also introduce performance overheads. If misused, it can result in the N+1 problem, where many additional queries are executed, leading to performance degradation. 599 | 600 | Also, when used in disconnected scenarios, such as within a web application, late queries can cause unexpected issues. 601 | 602 | ### Code Example: Sales Context 603 | 604 | Here is the C\# code: 605 | 606 | ```csharp 607 | 608 | public class SalesContext : DbContext 609 | { 610 | public DbSet Orders { get; set; } 611 | public DbSet Customers { get; set; } 612 | public DbSet Products { get; set; } 613 | } 614 | 615 | public class Order 616 | { 617 | public int OrderId { get; set; } 618 | public int CustomerId { get; set; } 619 | public virtual Customer Customer { get; set; } 620 | public virtual ICollection Products { get; set; } 621 | } 622 | 623 | public class Customer 624 | { 625 | public int CustomerId { get; set; } 626 | public string Name { get; set; } 627 | public virtual ICollection Orders { get; set; } 628 | } 629 | 630 | public class Product 631 | { 632 | public int ProductId { get; set; } 633 | public string Name { get; set; } 634 | public decimal Price { get; set; } 635 | public virtual ICollection Orders { get; set; } 636 | } 637 | ``` 638 |
639 | 640 | ## 11. How do you install or upgrade _Entity Framework_ in a _.NET_ project? 641 | 642 | To **install** or **upgrade** Entity Framework (EF) in your .NET project, you can use **NuGet Package** Manager in Visual Studio or the Command Line Interface (CLI). 643 | 644 | ### Visual Studio (VS): NuGet Package Manager 645 | 646 | 1. **Access Package Manager**: Go to `Tools` > `NuGet Package Manager` > `Manage NuGet Packages for Solution...`. 647 | 2. **Install**: In the `Browse` tab, look for `EntityFramework`, then click `Install`. 648 | 3. **Upgrade**: Navigate to the `Installed` tab, select `EntityFramework`, and choose `Update`. 649 | 650 | ### VS Code: NuGet Package Manager 651 | 652 | 1. **Install**: In the terminal, use `dotnet add package EntityFramework`. 653 | 2. **Upgrade**: Run `dotnet add package EntityFramework --version 6.x`. 654 | 655 | ### Command Line Interface (CLI) 656 | 657 | 1. **Install**: Run `dotnet add package EntityFramework`. 658 | 2. **Upgrade**: Specify the version using `dotnet add package EntityFramework --version 6.x`. 659 | 660 | ### Benefits of Multi-Level Flexibility 661 | 662 | - **Error Handling**: NuGet provides feedback on potential errors as you type, reducing the likelihood of version conflicts or wrong selections. 663 | - **Version Control**: You can specify exact versions, providing stability in your project, or opt for dynamic updates. 664 | - **Efficiency**: Multiple install or upgrade tasks can be executed in one command, streamlining workflows. 665 |
666 | 667 | ## 12. What is the difference between _local_ and _global configuration_ in _EF_? 668 | 669 | **Entity Framework** operates with both global and local configurations to handle the mapping between your data schema and the domain model. 670 | 671 | ### Global vs Local Configurations 672 | 673 | - **Global Configuration**: Embodies the primary mapping logic between classes and database tables. Global configurations are implemented during **Model creation**. 674 | 675 | - **Local Configuration**: Offers more granular control and at times, can override global setups. This happens during the **initializer's seeding phase**. 676 | 677 | ### Code First Vs Database First 678 | 679 | - **Code First**: In the Migrations model, the `DbContext` offers an `OnModelCreating` method, which is the location for both global and local configurations. 680 | 681 | - **Database First**: In this model, the `.edmx` file encompasses global definitions (the main `.edmx` file) and may have local definition files (model-specific `.edmx` files). 682 |
683 | 684 | ## 13. What is the purpose of the _Entity Framework connection string_? 685 | 686 | The Entity Framework connection string, typically stored in a project's `app.config` or `web.config`, is necessary to **establish a connection between the application and the database**. 687 | 688 | ### Key Elements 689 | 690 | - **Data Source**: Essential for server location, and can be a literal source or a path to a file or database. 691 | - **Initial Catalog**: Specifies the database to target at the start. 692 | - **User ID** and **Password**: Required for an ID-assisted secure connection. 693 | - **Integrated Security**: A true/false flag often employed with Windows authentication. 694 | 695 | ### Configuration Examples 696 | 697 | - **Database File**: Ideal for simpler applications leveraging local storage. 698 | - **Windows Security**: When paired with `Integrated Security=true`, uses Windows credentials. 699 | - **Provide Both**: Acceptable when a precise database, ID, and password are necessary. 700 | 701 | ### Potential Issues 702 | 703 | - **Hardcoded Connection Strings**: Resists configuration modifications or environment-specific adjustments. 704 | - **Security Risks**: Publicly available IDs or passwords could compromise the database's safeguarding. 705 | 706 | ### Best Practices 707 | 708 | - **Externalize Connection Strings**: Leverage app or web.config files to hold the strings. This externalization promotes maintainability and diminishes security threats. 709 | - **Parameterized Constructs**: Use SQL parameters to fortify the link's integrity while thwarting potential assaults. 710 | - **Secure Storage Strategies**: Tactics such as an encrypted configuration file or a safe data storeroom ensure enhanced security levels. 711 |
712 | 713 | ## 14. How do you switch between different _databases_ using _EF_? 714 | 715 | While developing **ASP.NET** applications, you might need to **switch between different databases** in an **Entity Framework** (EF) context. 716 | 717 | Here are two common approaches to accomplish this: 718 | 719 | 1. **Code-based Selection**: Perfect for instances where the choice of database is known at compile-time. You use an `app.config` or `web.config` to specify the database connection. 720 | 721 | 2. **Run-time Database Selection**: Ideal for scenarios where the database to be used can only be determined at runtime. 722 | 723 | ### Code-Based Selection 724 | 725 | In environments where the database choice is known at compile-time, you can use **Conditional Compilation Directives** to select the appropriate EF context, using tools such as `#if DEBUG` to differentiate between, say, a development and a production environment. 726 | 727 | 728 | - **Code CSHarp** 729 | 730 | ```csharp 731 | #if DEBUG 732 | using (var db = new DevelopmentDbContext()) 733 | { 734 | // Database logic for development environment 735 | } 736 | #else 737 | using (var db = new ProductionDbContext()) 738 | { 739 | // Database logic for production environment 740 | } 741 | #endif 742 | ``` 743 | 744 | ### Run-time Database Selection 745 | 746 | You can **set the EF context** at runtime, allowing the application to **dynamically switch** between different databases based on user inputs or other factors. This approach gives more flexibility and is often used in applications where the database might change at runtime. 747 | 748 | - **Code CSharp** 749 | 750 | ```csharp 751 | using System.Data.Entity; 752 | 753 | public class DbContextFactory 754 | { 755 | public DbContext GetDbContext(DatabaseType type) 756 | { 757 | switch(type) 758 | { 759 | case DatabaseType.Production: 760 | return new ProductionDbContext(); 761 | case DatabaseType.Staging: 762 | return new StagingDbContext(); 763 | default: 764 | return new DevelopmentDbContext(); 765 | } 766 | } 767 | } 768 | 769 | public enum DatabaseType 770 | { 771 | Production, 772 | Staging, 773 | Development 774 | } 775 | 776 | // Somewhere in your code... 777 | // var dbFactory = new DbContextFactory(); 778 | // var db = dbFactory.GetDbContext(DatabaseType.Production); 779 | ``` 780 |
781 | 782 | ## 15. Can you configure the _pluralization_ and _singularization conventions_ in _EF_? 783 | 784 | **Entity Framework** allows developers to tailor singular-to-plural and plural-to-singular naming conventions using the **PluralizationService**. 785 | 786 | ### PluralizationService in EF 787 | 788 | The PluralizationService uses a set of rules and applies them in reverse for singularization. For instance, "**dogs**" would be singularized to "**dog**". 789 | 790 | EF's pluralization and singularization rules exist in the `System.Data.Entity.Design` namespace. Custom rules can be adopted by inheriting from the `PluralizationService` base class. Several approaches, such as modifying or replacing rules, are available for advanced customization. 791 | 792 | ### Using `System.Data.Entity.Design` 793 | 794 | If you choose to work with `System.Data.Entity.Design`, you can apply customized conventions by accessing the singleton service **Default** and replacing or augmenting rules using standard methods. Taking "child" as an example, the method to "singularrize" it will act as: 795 | 796 | ```csharp 797 | var singular = Default.PluralizationService.Singularize("child"); 798 | ``` 799 | 800 | ### Using NuGet Package: "System.Data.Entity.Design" for older EF versions 801 | 802 | EF Core doesn't support the PluralizationService method natively, but for older versions, you can install the NuGet package **System.Data.Entity.Design**. 803 | 804 | For EF Core, you can use **EF Core Power Tools**, which equips EF Core with pluralization support. 805 | 806 | ### Code Example: Singularizing "Children" 807 | 808 | Here is the C# code: 809 | 810 | ```csharp 811 | using System.Data.Entity.Design.PluralizationServices; 812 | using System.Globalization; 813 | 814 | var pluralService = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en-us")); 815 | var singularChild = pluralService.Singularize("children"); 816 | ``` 817 | 818 | Upon running this code, **singularChild** will hold the value "**child**". 819 |
820 | 821 | 822 | 823 | #### Explore all 100 answers here 👉 [Devinterview.io - Entity Framework](https://devinterview.io/questions/web-and-mobile-development/entity-framework-interview-questions) 824 | 825 |
826 | 827 | 828 | web-and-mobile-development 829 | 830 |

831 | 832 | --------------------------------------------------------------------------------