Entity Framework Interview Question And Answers


In .NET applications, whether for web or desktop, ADO.NET is a classic yet powerful method for accessing databases and needs a lot of coding. In other words, all of the work will be done manually. To streamline the process, Microsoft has invested in the Entity Framework to automate the database technique. Entity framework is an open-source ORM for the .NET application that has a set of utilities and mechanisms that will work towards optimizing the data-driven apps.

It is one of the essential concepts in the MVC model. By using the tables and columns, developers can streamline the mapping between the several objects in the software application. It uses the objects of the domain-specific classes while ignoring the database tables. Also, you should know that it uses columns for storing the data. Unlike traditional apps, designers can use the EF to maintain and develop data-oriented apps with a bit of coding and a high level of absorption when dealing with the data.

Know More About Entity Framework

There are several Entity Framework Features which one can benefit from. The primary benefits and features of the framework have led to the development of one of the toughest Entity Framework Interview Questions and Answers for 2 years experience. These questions help employers to hire the best professional that their company needs. Let us look at some of the best features of the EF.

  • Cross-Platform: it may be the primary benefit of the platform. EF is the primary cross-platform framework you can run on Linux, Mac, and Windows.
  • Modeling: EF creates an EDM based on the POCO entities. These have different properties of different data types. It uses the model when saving or querying the entity data to the underlying database.
  • Saving: EF deploys the DELETE, INSERT, and UPDATE commands to the database based on the changes that have occurred to the entities when you call the SaveChanges() method. The framework also offers the asynchronous SaveChangesAsyn() method.
  • Change Tracking: EF tracks the changes which happen to the instances of the entities, and it should submit to the database.
  • Querying: EF allows developers to use the LINQ queries to retrieve the data from the underlying database. These databases provider translates the LINQ queries to the database-specific query language. Entity Framework allows the execution of the raw SQL queries directly to the database.
  • Concurrency: Entity Framework utilizes optimistic concurrency as a default. It protects the overwriting changes other users make since data was acquired from the database.
  • Configurations: EF allows developers to configure the EF model with the help of data annotation attributes or the fluent API for overriding the default conversations.

Now that you have brushed up your basics let us look at the top Entity Framework Interview question and answers.

What Do You Mean by the Entity Framework?

An Entity Framework (EF) is an open-source ORM (Object-Relational Mapper) from Microsoft. It allows developers to work with .NET applications and other domain-specific objects. It helps streamline mapping between different objects within the software by providing tables and columns.

A framework uses objects of domain-specific classes and also provides an option to store and access data in the database automatically. This concept is from MVC. However, the Entity framework does not focus on the original database columns and tables used to store data. This makes it easier to operate an abstraction of a higher level while creating new applications or maintaining the existing ones.

Why should we use the Entity Framework?

It is a kind of a problematic task when it comes to writing and managing ADO.NET codes. Therefore, Microsoft introduced the Entity Framework to make this tedious task more manageable. Entity Framework reduces a significant amount of code-based tasks by providing relational data in the form of domain-specific objects.

What is ADO.NET EF?

ADO.NET Entity Framework is an ORM framework that allows us to work with different relational databases, such as Oracle, MYSQL, SQL Server, DB2, etc. It enables us to work with the data either as objects or entities.

Apart from this, ADO.NET also helps create senior abstract object models on the top of ADO.NET components. This eventually enables us to use advanced level domain objects, such as customers, suppliers, etc.

How will you differentiate ADO.NET from Entity Framework?

We can differentiate ADO.NET from Entity framework using the following table:

ADO.NETEntity Framework
ADO.NET is fast.Entity Framework is comparatively slower.
It creates several data layer codes.It does not create any data layer codes.
It does not create codes for the data access layers, intermediate layers, and mapping codes by itself.It automatically creates codes for the data access layers, intermediate layers, and mapping codes. This eventually helps developers cut down the development of work and time.

What are the main advantages and disadvantages of the Entity Framework?

Advantages:

  • It provides a wide range of prototypes that helps write object-oriented codes.
  • It includes auto migration support that helps configure or manage a database easily and quickly.
  • It provides many alternate commands that help shorten codes and make a coding job a lot easier.

Disadvantages:

  • It is a slower form of ORM.
  • If a user does not use raw SQL codes, things might become difficult.
  • It directs the shape of the entire model when it comes to difficult projects. Additionally, cleaning a model is not possible without an ORM technique.

Illustrate the main components of the Entity Framework Architecture.

The following are the main components of the Entity Framework Architecture:

Entity Data Model (EDM): It consists of the three parts, such as storage model, conceptual model, and mapping.

Entity SQL: It is an alternate query language that you can use in Entity Frameworks along with L2E. However, L2E is comparatively more straightforward.

LINQ to Entities (L2E): It is a query language that helps write queries against the object, which further helps to retrieve the entities based on the definitions specifies in the conceptual model.

Entity Client Data Provider: It is the layer that helps convert the L2E queries to SQL queries to easily understand by the database. Additionally, it can interact with the ADO.NET data provider to transfer or retrieve data from different databases.

Net Data Provider: It is another layer that helps interact with the database by using standard ADO.NET.

Object Service: It is an entry point into the database that you can use to access and send back the data when needed. It helps convert the data coming from an entity client data provider into an entity object structure.

What is the role of an Entity Client Data Provider?

Responsibility of Entity Client Data Provider is to convert the LINQ to Entities or Entity SQL queries to a SQL query, which is understood by the underlying database. This finally communicates with ADO.NET Data Provider which in turn talk to the database.

8 What is the meaning of Pluralize and Singularize in Entity Framework?

Pluralize and Singularize give meaningful naming conventions for objects.

We will get this option while adding an edmx file. On selecting this option Entity Framework will adhere to Singular or Plural coding conventions.

What are the primary functions of the Entity Framework?

The following are the primary functions of EF:

  • It helps map domain classes to the database schema.
  • It keeps track of changes in the entities.
  • It helps execute LINQ queries to SQL.
  • It stores the changes stats to the database.

What is defined by the migration in context with the Entity Framework? Also, name its types.

Entity Framework contains a migration tool that automatically helps users update the entire database whenever there is a change in the model. The tool updates the database without losing the stored data or any database objects.

There are mainly two types of migration in Entity Framework:

  • Automated Migration
  • Code-based Migration

What are the processes to load related entities in the Entity Framework?

We can use any of the following processes to load related entities in the Entity Framework:

Lazy Loading: This process delays the loading of related objects until there is a requirement for them. Lazy loading only returns objects needed by the user, and all other related objects are only returned when required in the process.

Eager Loading: This process mainly takes place when we query for an object. Eager loading returns all the related objects. Additionally, all the related objects are automatically loaded with the parent object.

Explicit Loading: This process only occurs when we want to use lazy loading, even when we have already disabled lazy loading. To process explicit loading, we are required to call the relevant load method on the related entities explicitly.

What are the different types of inheritance That Entity Framework Supports?

There are mainly three types of inheritance that Entity Framework supports, such as:

Table per Hierarchy (TPH): This type of inheritance depicts a single table for the entire inheritance hierarchy class. Besides, the table consists of a discriminator column that helps distinguish different inheritance classes. It is the default inheritance mapping technique in Entity Framework.

Table per Type (TPT): This type of inheritance depicts a separate or specific table for all and each domain class.

Table per Concrete Class (TPC): This type of inheritance depicts a single table for a single concrete class, but it does not include the abstract class. Therefore, if an abstract class is inherited in various concrete classes, then every concrete class table will have the same properties as the abstract class.

What are the primary parts of the Entity Data Model?

There are mainly three parts of the Entity Data Model, such as:

  • Storage Model
  • Conceptual Model
  • Mapping

What do you mean by a model in context to Entity Framework?

A model is nothing but a class mainly used to represent the data. In context to EF, a model represents the data from a table inside the existing database.

Example: The following codes display the basic customer model:

public class Customer  
{  
  public int ID { get; set; }  
  public string Name { get; set; }  
  public DateTime JoinDate { get; set; }  
} 
 

How will you differentiate LINQ from Entity Framework?

We can differentiate LINQ from Entity Framework with the help of the following table:

LINQEntity Framework
It only operates with the help of the SQL Server Database.It has various databases, such as SQL Server, MYSQL, Oracle, DB2, etc.
It supports one to one mapping between entity classes and the relational tables.It supports one to one, one to many, and many to many mapping types between the entity classes and the relational tables.
It maintains a relation by creating a .dbml file.It first creates the .edmx file. After that, it maintains a relation using three types of files: .ssdl, .msl and .csdl.
It does not support complex types.It supports complex types.
It cannot generate a database by using the model.It can generate a database using the model.
It enables users to query the data with DataContext.It allows users to query the data with DbContext, ObjectContext, and EntitySQL.
It contains a tightly coupled mechanism.It contains a loosely coupled mechanism.
It is mainly used for faster application developments with SQL Server.It is primarily used for faster application developments using SQL Server and other databases like MYSQL, Oracle, DB2, etc.

How will you define the Conceptual Model?

The conceptual model is usually the model class that consists of relationships. This type of model remains independent of the database structure.

What is DBContext?

When we create an edmx file, it will have the list of entities and context class which will be derived from DBContext class.

How will you explain the Storage Model?

You can explain the storage model as the database design model that consists of database tables, stored procs, views, and keys with relationships.

What do you understand about EDM? Also, list the process for creating EDM.

EDM in EF is a short form of ‘Entity Data Model’. It is the entity-relationship prototype that helps assign basic prototypes for the data utilizing various modeling procedures. Additionally, it is referred to as a collection of core principles that define data that disregards its aggregated form. In short, it is nothing but a simple connection formed between the database and the prototype.

The following are the steps that help create an Entity Data Model:

  • First, we need to right-click on the project’s name given in the solution explorer tab.
  • Next, we need to click on ‘Add a new item from the menu’.
  • After that, we have to select the ADO.NET Entity Data Model arrangement or any template.
  • Finally, we must specify a name for the model and click on the ‘ADD’ button.

That is how we can create EDM in Entity Framework.

What is EF Data Access Architecture?

The ADO.NET Framework supports two models of Data Access Architecture:

  • Connection Oriented
  • Disconnected

EF uses the Disconnected model (doesn’t leave a connection open). Since you work with data and make desired changes and then you perform the Save Changes. In N-tier applications a context either produces entities or saves entities, not both. It also produces entities that get serialized, and the context is disposed of. Entities that return from the client application are deserialized and re-attached to new context instance that saves their changes.

Enlist all the steps required to retrieve data from the MVC database with the help of Entity Framework.

The following are the steps to retrieve data from the database in MVC with the help of Entity Framework:

  • First of all, we need to create a new project.
  • Next, we need to add an Entity Framework reference from the NuGet package manager.
  • Then, we need to create a new class within the model inside the table structure.
  • After that, we need to add a connection string in the web.config.connection. It has to match with the context.
  • Next, we need to open the Global.asax.cs class, and implement the new namespace of EF. Then, we need to initialize the database.
  • now, we need to right-click on the Controller folder and add a new controller along with the model reference in section namespace.
  • Finally, we need to right-click on the Controller name and add the sections we want to retrieve.

That is how we can view or retrieve the data from the database in MVC using EF.

What do you mean by dbcontext and dbset?

DbContext is referred to as a class in the Entity Framework API that helps create a communication between the database and the domain/entity class. In simple terms, it is a class mainly you can use for communicating with the database.

DbSet is also referred to as a class that helps represent an entity set for different operations, such as creating, updating, reading, and deleting. The context class in DbContext must include the DbSet type properties for all such entities that help join database tables and views.

How will you define POCO classes concerning the Entity Framework?

The term POCO is a short form of ‘Plain Old CLR Objects’. However, it does not mean that the classes used here are plain or old. POCO classes are usually the classes that do not include any reference specific to the EF or .NET framework. The POCO entities are referred to as the available domain objects in the Entity Framework application.

Unlike standard .NET class, POCO class of any object is independent of a framework-specific base class. POCO classes support various LINQ queries. Moreover, you should know that the derived entities of the Entity Object supports them.

What are the different types of approaches that you can use in Entity Framework?

There are mainly three types of approaches that we can use in Entity Framework, such as:

  • Model First Approach
  • Code First Approach
  • Database First Approach

How will you define the Code First approach and the Model First approach? Also, enlist their advantages.

Code First Approach: In Entity Framework, the Code First approach is mainly used to create a model and its relationships using classes, which further help create a database. This enables developers to work in an object-oriented manner without thinking about the structure of the database. In this approach, the developers first write POCO classes and then create the database with the help of these POCO classes. Most developers following Domain-Driven Design (DDD) technique use the Code First approach.

Advantages of Code First Approach:

  • It allows developers to decide the database structure according to business objects, making it more beneficial for smaller applications.
  • It enables developers to decide which classes should be serialized. It also allows us to specify the collection to eager load.

Model First Approach: On the other side, you can use the Model First approach to create model classes and their relationships using ORM. Once you successfully create the model classes and relationships, the physical database is created with the help of these models.

Advantages of Model First Approach:

  • It offers flexibility for designing the Entity Models separately and provides options to improve them in further stages.
  • It does not use many databases because we can create model classes by drawing them using the EDMX designer.

Define the database first approach.

In terms of the Entity Framework, the Database First approach is the method of generating an entity model from the available database. The primary motive of this approach is to lower the number of codes to be written. This approach mainly helps create domain and context classes based on the existing classes.

What are the advantages and disadvantages of Database First Approach?

Advantages:

  • Easy to create entity models if there is an existing database.
  • Preferred approach for data intensive applications.

Disadvantages:

  • Once we create an edmx file from an existing database, huge pile of code is generated.
  • If we want to add the additional functionality to the models generated, we need to extend the models.

Which, according to you, is the best approach in the Entity Framework?

There is no particular approach that can be referred to as the best approach in Entity Framework. The selection of the development approach primarily depends on the project requirements and the project’s types. If there is the database’s existence, then it is good to use the Database First approach. If there is no database and the model classes, then the Model First approach is the best selection. If there is the availability of the domain classes, the Code First approach is the most suitable choice.

Define the .edmx file in the context of Entity Framework.

In the context of Entity Framework, a .edmx file is a simple XML file that may contain storage models, conceptual models, and the mapping between them. It contains all the mapping information of how objects map with SQL tables. Besides, it can include information required by ADO.NET Entity Data Designer to render a model graphically.

What is meant by database concurrency and how to handle it?

EF’s database concurrency is defined as the scenario when multiple users access and modify the same data in the same database simultaneously. The systems that protect the consistency of data in such situations are known as concurrency controls.

The database concurrency is usually handled by implementing optimistic locking. To implement the locking, we must first right click on the EDMX designer and then set the concurrency mode to Fixed. After making this change, we will get a positive concurrency exception error if there is a concurrency issue.

What is Optimistic Locking?

Optimistic Locking is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) and check that the version hasn’t changed before you write the record back. When you write the record back you filter the update on the version to make sure it’s atomic. (i.e. hasn’t been updated between when you check the version and write the record to the disk) and update the version in one hit.

If the record is dirty (i.e. a different version to yours) you abort the transaction and the user can restart it.

This strategy is most applicable to high-volume systems and three-tier architectures where you do not necessarily maintain a connection to the database for your session. In this situation the client cannot actually maintain database locks as the connections are taken from a pool and you may not be using the same connection from one access to the next.

What are the different types of properties supported in Entity Framework?

There are mainly three types of properties supported in Entity Framework, such as:

  • Navigational Property
  • Complex Property
  • Scalar Property

How will you define Mapping in Entity Framework?

The mapping in Entity Framework is defined as the information that explains how the conceptual models are mapped to the storage models.

How to return multiple results set in Entity Framework?

One can use the following pattern to return multiple result sets:

  • One can make the database in the SQL Server or Local DB and occupy the tables by implementing the following script file, STOREDB.sql, utilizing SQL Server Management Studio or SSMS or Visual Studio.
  • Implementation of the script will add 2 collected processes into the database. Choose those procedures from the functions list in the Add tab.
  • Right-click on any blank portion on the Entity Framework developer and choose the Model browser. Now alter the GetProductCM_Result to Product_SprocResult. Save the StoreDBModel.edmx file. Discover the FunctionImportMapping nodes within edmx:Mapping/../En

What do you understand about LINQ to Entities?

LINQ to Entities (L2E) is defined as one of the popular query languages in Entity Framework. L2E mainly helps write queries against the objects to retrieve entities based on the conceptual model’s definitions.

How to prevent sql injection in entity framework?

The SQL injection is a technique for code injection that can attack data-driven applications and can destroy the database. The SQL injection is one of the most commonly used web hacking procedures that injects malicious codes in the SQL statements through the input of the web page.

LINQ helps to prevent SQL injection in the entity framework. This happens due to the passing of all data to the database through the QL parameters. LINQ queries are not susceptible to the attacks by SQL injection as they are made by implying concatenation or manipulation of the string.

What is a fluent API in MVC?

Fluent API is a way of specifying the configuration of the model that covers everything executed by the annotations of the data. Fluent API and data annotations may be used together, but more preference is given by the Code First to Fluent API, then data annotations and finally to the default conventions. Fluent API is a way to configure the domain classes.

The Fluent API of the Code First is accessed by overriding the OnModelCreating method of the derived DbContext. Fluent API offers more configuration functionality than the DataAnnotations. Fluent API allows the user to configure the properties of the entities.

What is the proxy object?

Proxy Objects act as an intermediary between an accessible object and the client. Proxy Objects monitors the lifespan of the accessible objects and forwards the calls to the objects when it is not destroyed. Proxy objects check the availability of accessible objects whenever a client calls an IAccessible property to know proper information about the object.

The proxy object passes the requests of the client to the accessible object. When an accessible object is not present or is destroyed, an error is returned by the proxy object. The proxy object is always clear to the client.

What is the use of Migrations History Table in Entity Framework?

Migration History Table is utilized by Code First Migrations to collect details regarding migrations that are required to apply to the Database. By revert, the denomination of the table within the Database happens to be _MigrationHistory and it is made during the application of the first migration to the Database. In Entity Framework 5 it was a method table for the application being utilized in the Microsoft SQL Server database. However, this utilization of it has been altered in Entity Framework 6 and Migration History Table is no more a salient system table.

Explain the difference between Add and AddRange?

Difference between Add and Add Range in Entity Framework:

AddAdd Range
Add is used to insert one element at a time in a collection.AddRange is used to add multiple elements.
The add method inserts the item at the end of a collection.AddRange method is used to insert a set of records into a collection.
Add method is implemented for a new elementAddRange is employed in a collection that is already created

The addRange method is also used to add an array of nodes that are previously created in the collection.

What is a change tracker in Entity Framework?

By delinquency Entity Framework traces alterations of the filled entities throughout the lifespan of the context. A change tracker traces alteration when one adds new records, deletes or updates the existing records. It offers one all the details and information regarding updated entities being traced by the context and all the alterations are collected by the Dbcontext level.

Hence, the change tracker offers access to alter tracking operations and information for entity instances of the context which is being traced. Instances of these classes are usually taken from change tracker, and which are not developed to be directly created in one’s application code.

How can we do pessimistic locking in Entity Framework?

Pessimistic locking presumes that collision or concurrency issues will occur, so a bar is set on the records and later the data is reconditioned. One can execute pessimistic locking by identifying “IsolationLevel” in SQL server collected procedures, AFO.Net level or via utilizing proceeding scope object.

There are four types of locks one can acquire:

  1. Exclusive: when one wants to modify data without wanting anyone else to read the proceedings.
  2. Shared: when one wants to read-only without wanting to update any distinct transactions.
  3. Intent or demand locks: it is utilized to lock hierarchy.
  4. Update lock: when one wants to update procedures or operations which move via innumerable phases before the real occurrence of updating.

What do you mean by connected and disconnected data access in ADO.Net?

  • Dis- connected data access:

Through the Data Adapter object, disconnected data access is achieved. The dataset works separately from the database, and the data is editable.

  • Connected data access:

Through the Data Reader objects of the data-provider, you can have linked data access. It provides quick access to data, and it does not permit editing.

What other O/RMs can we use with .NET based applications?

The following O/RMs, we can use with .Net based applications are:

  • Dapper
  • N Hibernate
  • Entity Framework 6.x
  • Entity Framework Core

What do you mean by Dapper?

Dapper is a simple ORM for the .NET world. Dapper was shaped by the Stack Overflow team to address their issues and open source it. It’s a NuGet file that can be added to any .NET project for database operations.

What is automatic migration?

IEntity Framework supports habitual migration so that you don’t need to wander model changes physically. So, when you run the application, it will be handled by the EF.

What is Micro O/RMs?

A Micro ORM is architected to spotlight on the most significant task of working with database tables instead of creating, modifying the database schema, tracking changes etc. EF 6.x and EF Core both are O/RMs since they offer a full set of features.

What is the namespace used to include .NET Data Provider for SQL Server in .NET code?

The namespace System.Data.SqlClient is utilized to comprise.NET data provider for SQL server in .NET code.

Define Object Set?

Object Set a typed entity set which is used to perform create, read, update, and delete operations on a particular entity. An Object Set can only be generated from an Object Context instance. Object Set does not support the Entity SQL methods.

What is an Entity Graph?

Entity Graph is when one entity has a relation with another entity.