Entity Framework Interview Questions and Answers

If you are a Software Developer you probably have used or heard about Object Relational Mapping, also known as ORMs. Entity Framework is a good example of an ORM tool and it is currently the most popular ORM in the .NET world. Made by Microsoft, it keeps growing and becoming ever more effective by the day. There are lots of topics to discuss, but we will touch some basic and advanced Entity Framework interview questions.

Question: What is an ORM?

About this question: This is a common question to assess candidate’s understanding about what they are using and why.

Answer: ORM is an abbreviation of Object Relational Mapping. In computer science it describes a technique to convert data from one type, most usually data stored in a relational database, to an object oriented type.

References:

Why should we use an ORM?

About this question: This is common question to assess the candidate’s understanding of the pros and cons of using an abstraction layer such as an ORM. This helps the interviewer to understand how experienced a candidate is. A mature developer would not only know how to use a tool or technology, but above all, why he is using it.

Answer: ORM stands for Object Relational Mapping. There are two different worlds, so to say, one is the relational and the other is the object oriented. There is a lot of work to bridge these two worlds, this is called The Impedance Mismatch. An ORM works as the bridge.

So, ORK should allow developers to communicate with data structures without writing SQL scripts, for example, or implementing ADO.NET communication, which means a lot easier life than having to do this without an ORM tool.

Pros:

  • ORM saves a lot of time because: it’s easier to update, maintain, and reuse the code;

It comes with a lot of automation (database manipulation, I18N, etc).

  • ORM library is more flexible because: It fits into the developer’s natural form of coding (it’s your language!); it abstracts the DB system, so you can change it whenever you want; it allows you to use OOP as data inheritance without a headache.

Cons:

  • You have to learn a new library;
  • ORM is an 80/20 solution, in which 80% of users require only 20% of SQL functionality. But even considering that 80% of users use only 20% of SQL features, if the system grows the chances are high that you will have to violate the abstraction somehow.

Check the first answer in this stackoverflow question for more information.

What is the Entity Framework?

About this question: This question may be asked to assess the candidate’s basic view of Entity Framework.

Answer: The Entity Framework is an ORM tool which is highly used by the .NET community to map entities from database to Object Oriented models.
Developers can map classes to tables in a database, making it much easier to deal with the data stored there.

It is also about productivity, since it eliminates the need to write SQL statements such as SELECT, INSERT, UPDATE and DELETE.

References:

What is LINQ to SQL?

About this question: This question may be asked to see candidate’s understanding of what is “LINQ to SQL” and how it works as an ORM.

Answer: “LINQ to SQL” is a component of the Visual Studio which offers infrastructure for managing relational data as objects. If converts queries written in C # or Visual Basic to dynamic SQL. It provides an interface that allows you to map the database objects generating the classes to perform the operations using the LINQ syntax. Also allows you to make changes to the objects and update the database.

Main benefits of LINQ to SQL:

  • You can program the data access code directly in Visual Basic or C #;
  • Syntax and schema checking at compile time;
  • Support for tools to create queries (IntelliSense);
  • You do not have to wait until you run to know if the query is correct. You check it at compile time.

https://msdn.microsoft.com/en-us/library/bb425822.aspx

If you want to configure your relational mapping of Entity Framework programmatically, what would you do?

About this question: This question checks how experience is the candide regarding configuring Entity.

Answer: It is highly recommended to use Code First configuration to define my models in code. Code first is an approach that enables you to describe a model programmatically. It is also interesting to point to the fact it is configured by exception, which means several conventions and defaults are at play.

Besides Code First, these are steps you should follow:

If you want to create a relational mapping configuration inside Designer which technique would you use?

About this question: ┬áThis question depends on candidate’s understanding of several ways of configuring the EF.

Answer: The Model First technique is the most indicated approach if database does not exists or Database First technique if database has been already created.

What is currently the latest version of Entity Framework?

About this question: This is a common question to assess how much the candidate is following the trends of the technology that they are using and how passionate they are to learn new things.

Answer: There are two versions of the Entity Framework: Entity Framework Core and Entity Framework 6.x.

Entity Framework 6.x (EF6.x) is a relatively mature, stable, and tested data access technology. EF6.x remains a supported product and will continue to see bug fixes and minor improvements for some time.

Entity Framework Core (EF Core) is a lightweight, extensible, cross-platform version of the Entity Framework. EF Core introduces many enhancements and new features when compared to EF6.x. At the same time, EF Core is a new code base and a new product.

EF Core maintains the EF6.x developer experience and most high-end APIs remain the same, so EF Core will look very familiar to anyone who has ever used EF6.x.

Check more information on the EF Core vs EF 6 comparison offered by microsoft.

Which are the pros and cons of the new Entity Framework Core 1.0?

Answer:

The main pros:

  • it allows one to execute code on Linux and MacOS environments.
  • it can work with NOSQL Databases.

The main cons:

  • it does not provide Lazy loading
  • It does not support stored procedures
  • no graphical modeling tools supported.

Check this stackoverflow example for more information.

What is lazy loading in Entity Framework?

Answer: Lazy loading is the mechanism used by Entity Framework to load information on demand. This mechanism makes the entities lighter because their associations are loaded only when the method that makes the associative data available is invoked. It means that when objects are returned by a query, related objects are not loaded at the same time, instead they are loaded automatically when the navigation property is accessed.

https://msdn.microsoft.com/en-us/library/dd456846(v=vs.110).aspx

What are the new features available in Entity Framework 6.x?

About this question: This question would depend on candidate’s understanding of new features in each new release of Entity Framework.

Answer: The main changes are:

  • asynchronous queries
  • stored procedure map
  • customizing code first conventions

Other additions can be seen in this tutorial.

Check also the post from Microsoft about Entity Framework Ninja Edition.

What is a Migrations in Entity Framework?

About this question: This question depends on candidate’s understanding of what is migrations and why we them need.

Answer: Migrations is an Entity Framework feature that allow one to have versions of the database, rollback versions and maintain a history. Migrations watches its POCO (Plain Old C# Object) classes and creates update and downgrade methods with the code needed to apply the changes. Something interesting is that one can use lambda expressions or pure SQL to change what the Migration will make.

https://msdn.microsoft.com/en-us/library/jj591621(v=vs.113).aspx

What is DbContext? What patterns are implemented by it?

About this question: The answer to this question depends on the candidate’s understanding of patterns and a deep knowledge about the Entity Framework.

Answer: DbContext is the main Entity class. It is responsible for interacting with data objects. This context class manages the entities objects at run time, which includes populating objects with data from a database, tracking changes, and persisting data to the database.

DbContext implements the Repository pattern as well as the Unit of Work pattern by default.

Check the excelente first answer for this stackoverflow question.

When would be a good idea to turn off lazy loading? How would you do it?

About this question: The answer to this question depends on the candidate’s practical understanding on how to configure Entity Framework lazy loading and why they would need it.

Answer: Sometimes Lazy Loading can lead to an excessive number of queries sent to the database, this could happen due to the fact that we do not have control over the execution of the queries that will be executed by the proxies classes.

A simple example: assuming a query is run to find cities and it returns 100 cities, each time we access the “neighborhood” property a new query is sent to the database. Thus, if we access the “neighborhoods” property of these 100 cities, 101 queries will be sent to the database (one query to return the 100 cities and 100 more queries to return the neighborhood of each county).

You could turn the lazy loading off by setting context settings property “LazyLoadingEnabled” to false.

How to resolve migrations conflicts?

About this question: This is a tough question that measures hands on past experience from the candidate working in teams, where migration conflicts can be common.

Answer: So, assuming you are in a developer position and you have found a conflict, you could:

  1. rollback your database to the state before any of the migrations.
  2. Put your database and migration at the same state as the database and migration of the other developer. That can be done by a target-specific migration.
    update-database -targetmigration:target -verbose
  3. Now, with a database that is identical to where the other left it, you should re-scaffold the migration.

For more information, check this excelente explanation given by Anders Abel.

What would happen if we try to map Entity Framework query to IQueryable model?

About this question: This question depends on understanding of what is IQueryable interface and how it works with Entity Framework.

Answer: If we execute a query in the database and we try to map it to IQueryable model, we will get a lazy loaded query inside the model, not an object oriented model. Only if we try to map our query to List or to array, EF will execute the query against the database and map it to our object oriented classes.

What is the feature of Entity splitting in Entity Framework for? Why should one use it?

Answer: The Entity splitting in Entity Framework allows one to separate properties of an object into more than a single table if necessary. It could be used to implement a better normalized database.

More detailed information can be found in the Introduction to Entity Framework from Microsoft.

Why should we use transactions? And how can we accomplish that?

About this question: This question is about the understanding of what transactions are and how one can use them with Entity Framework.

Answer: Transactions guarantee atomicity to a set of operations, i.e. either all of them will succeed, or all of them will fail. A classic example is a bank transfer, where two changes are necessary in your records:

  • reduce the balance of account A in X;
  • increase the balance of account B to X. If the first operation is performed, and soon after the system fails, your database will be inconsistent

With Entity Framework we can achieve it by using DbContext.Database.UseTransaction and DbContext.Database.BeginTransaction.

Check the transaction topic from the Microsoft introduction to Entity Framework.

How would you create a deep clone of a Dataset with the Entity Framework built in functions?

About this question: This question helps to measure how much understanding of EF built in functions the candidate has.

Answer: You can create a deep clone using the Clone method. It will create a new object with same properties and new instance.

How to change the state of an entity to remove it from database?

About this question: This question depends on practical experience of using deep state method of Entity Framework’s entities.

Answer: You could achieve it by changing the state of the entity to EntityState.Deleted. But it is not a great solution because you will not remove child elements of this entity. If that is your intention, it would much be better to use the Remove method.

Check this Microsoft Forum about this subject.

How would you call an stored procedure in a DbContext?

Answer:

DbContext API provides methods to execute database queries and commands in native SQL. The importance of these methods goes beyond the fact that they allow executing your own native queries, but they also allow one to access Stored Procedures.

So, calling a stored procedure could be achieved by calling the SqlQuery method:

DbContext.Database.SqlQuery<YourEntityType>(“storedProcedureName”,params);

Check this post from Diego Vega on the Microsoft blog to have a much more detailed view on this.

What is property annotation method in EF?

About this question: This question depends on candidate’s understanding about the configuration and mapping of fields in Entity Framework.

Answer: Property annotation is a configuration method inside the Entity Framework that allows developers to describe fields and properties as a database configuration. It is implemented by attributes.

Take a look at the Entity Framework Tutorial page on Data Annotation

How can we describe maximum length of characters using property annotations?

About this question: This question depends on understanding what specific attribute is using for describing maximum length of characters.

Answer: It can be achieved by [MaxLength(number of characters, error message)] also we could describe minimum length by attribute MinLength.

[MaxLength(75)]
public string name { get; set; }

[MaxLength(75),MinLength(8)]
public string name { get; set; }

http://www.entityframeworktutorial.net/code-first/maxlength-minlength-dataannotations-attribute-in-code-first.aspx.

We wish you a very good interview.

Leonardo Campos
 

Hi, besides writing about Java, I’m one of the guys behind this website alongside with Anselmo.
I’ve being working with IT for the last, let’s say, 17 years. About 10 of them as a Software Developer. The last 7 years my role has been a bit more managerial. I have being involved with Technical Interviews for quite a while now and have helped the hiring of pretty awesome developers.

Click Here to Leave a Comment Below 0 comments