Entity Framework Interview Questions


1. What is “code first” in relation to Entity framework?

Entity framework uses the process of “code first” that maps database tables to data models. The data models in your .NET project are actually classes that represent the structure of your database tables. This code is used to work with your database, so you don’t need a direct connection to your database in each of your class methods.

2. What is the difference between old ADO .NET and Entity framework coding techniques?

When you used ADO, you connected to the database and had to define a stored procedure or query to retrieve data. With Entity framework, you don’t have to be “blind” when it comes to your tables. ADO did not allow you to get the table structure. With code first, you already have the table structure and Entity framework connects to the database and hides any connection processes. With Entity framework, you’re more aware of the database structure, which helps you avoid any coding mistakes. In addition, if the table structures change, Entity framework updates the data models for you during a refresh.

3. What is LINQ?

Language-Integrated Query (LINQ) is a way to query data without cumbersome stored procedures. Previously, programmers needed to create stored procedures and then call these stored procedures from their code. With Entity framework, you can pull data and query it using language similar to SQL.

4. How is data retrieved?

The difference between older retrieval methods and current Entity framework retrieval methods is that you can now (with Entity) retrieve data as objects. The objects represent the tables (or linked tables) in your database. Instead of iterating through several columns and rows, you just use your class data models. For instance, if you have a table named “users,” you can use the “users” class instead of working through each data set after your query.

5. Can you run SQL statements in an Entity framework environment?

Yes, you can also run SQL query statements. You can use the “ExecuteStoreCommand” method to run SQL on your database. This is usually a secondary option from running simple LINQ on your Entity framework code. You can also run stored procedures from a database.

6. How do you create a database model?

Visual Studio has a database modeler available. You can create a database model from scratch, or you can query the database for the models. If you have a database already, you simply pull the database structures from your code and Entity framework will automatically set up the class data models.

7. Does Entity framework support primary and foreign keys?

Yes, Entity framework supports both types of primary and foreign keys. You can define these in your database tables and import them to your model classes. If you don’t already have a database set up, you can create these keys in your data model classes and their respective data modeling classes.

8. How do you mark a data column as required by the database?

You can “decorate” your data models. The “Required” decoration marks a field as required. Before a user can submit the data to the database, the user must have this field entered. You can also auto-generate required fields in your code, so the code automatically adds the required data.

9. What is lazy loading?

Lazy loading is a way to return only objects that are used. When you query the database model, lazy loading only returns the immediate tables needed by the user. All related tables are returned when they are used. This means you can reserve memory and storage when you work with large programs. It also means that objects are created until you need them, so it makes your program faster.

10. What is eager loading?

Eager loading is the opposite of lazy loading. When you query for objects, eager loading returns all of the objects including the related objects. For instance, when you query a list of customers and orders, eager loading loads all objects including the customers and the orders instead of just what you originally need (customers).

11. What is a navigation property?

A navigation property points to related tables in your database model. For instance, if you have a customer table that relates to the orders table, the navigation property points from the customers table to the orders table. While the primary and foreign keys are physical properties of the table, the navigation properties are a logical part of a data model. When you view the Entity framework model, you can view the navigation properties to better understand the structure of your tables.

12. What is a scalar property in your data model?

A scalar property is similar to a scalar property in the database. A scalar property points to one location in the table.

13. What is a complex data type?

A complex data type occurs when you need to point to another data object from one data object. For instance, if you have several tables that require an address, you can turn those addresses into a table of addresses. You then point your address columns to the new address table, which creates a complex data type. You will likely have complex data types in every .NET Entity framework project, because it makes it easier to relate one table and data model to another without creating cumbersome code.

14. Overall, what is Entity framework?

Entity framework is a type of ORM (object relational mapping) that connects classes with database objects. It makes it easier to work with databases and tables without worrying about columns and rows. ORM makes it easier for you to query databases using LINQ, and you do not need to worry about your database connection. Additionally, you can create programs that are unaware of the database and its connection or type (Oracle, SQL Server or MySQL). Entity framework takes care of all of the back-end connection so you can worry about the queries and data.



1. What is Entity Framework?

Microsoft Entity Framework (EF) is an Object Relational Mapping framework that provides an abstraction layer (a kind of mapping) between two incompatible systems (i.e. Object oriented programming languages with Relational databases). It enables us to interact with relational data in an object oriented way, meaning we can retrieve and manipulate data as strongly typed objects using LINQ queries.

2. What are the advantages of using Entity Framework?

Main advantages of Entity Framework are:

Separation of Concerns (SoC).
LINQ is used as a common syntax for all object queries.
Code Auto-Generation.

3. What is Entity Framework(EF) Core?

Entity Framework 7 rebranded as Entity Framework Core 1.0 is basically an object-relational mapping framework that allows us to communicate with database using .NET objects. It’s a lightweight, open-source and extensible framework for targeting .NET Core applications.Entity Framework Core

Entity Framework Core 1.0 has following additional features:

Cross Platform i.e. can work with .net core application built for MacOS or Linux.
Designed for disconnected/web services.
Entity Framework Core is cloud optimized.
EF Core is Device Optimized as being lightweight can work with SQLite.
Support for relational and non-relational databases.
EF Core also has Fluent API that enables a user to override the OnModeCreating strategy on a user’s context and makes it easy to figure the convention model.
Built-In convention that effectively builds an initial model based on the entity classes.
The EF Core features data annotations that are added to entity classes or properties to influence the EF model.
It also has Snapshot change tracking properties based on recording the initial values of an entity as it is retrieved from the database.
Notification change tracking enables a user’s entities to signal the change tracker in case property values are modified.
Connection resiliency that automatically retries any failed database commands. Connection resiliency comes in handy for connection to SQL Azure which is prone to transient failures.

There are many key features those were available in EF 6.x but not included in Entity Framework Core 1.0.

No Lazy Loading.
Group By Translation – If query includes a group by clause, it will be omitted.
Not Supporting stored procedures.
No Graphical Modeling Tools supported.
Spatial Data Types (a wrapper around a COM library).
Simple Command Interception.

4. Entity Framework uses DbContext, How is it different from Object Context?

DbContext can be used for code first while Object Context doesn’t. It exposes the most commonly used features of ObjectContext.

5. What’s new in Entity Framework 6?

Customizing Code First Conventions.
Logging of database commands.
Stored Procedure Mapping.
Asynchronous Queries and Save support.

With EF6, in applications with lots of tables and relationships defined, our context objects open faster. We should also be better insulated from dropped connections (at least, if the drop is transient and not permanent — nothing is going to help there).  EF6 also generates SQL faster from LINQ queries than before (though it’s the same SQL that’s being generated as in earlier versions of EF, so your actual data access won’t be any faster or slower).

6. Why do we use Lazy Loading in Entity Framework?

Entity Framework facilitates us to avoid huge, deep, highly-relational queries, so that the data will not heavy on the web.
As by default, lazy loading option is enabled in Entity Framework but that can cause major performance issues in some scenarios .
We can disable Lazy loading (or in other words, enable eager loading) by using the following code:

ContextOptions.LazyLoadingEnabled = false;

7. If we have not followed proper conventions in Code First approach, then how we can mark a field/property as primary key?

This can be done using a simple attribute [Key]

8. How we can enforce number of characters (minimum or maximum) for a field using Entity Framework Property Annotation method?

We can easily use property annotation of [MinLength] and [MaxLength] to enforce minimum or maximum number of characters for a specific field respectively.

9. How we can use a property for an Entity that is not mapped to database in Code First Approach?

In Code First Approach, all properties are normally mapped to database. But in certain scenarios, if we don’t want a specific property to be mapped to database, Entity Framework provides us with NotMapped attribute for annotation.

10. Can you describe the feature of split entity in Entity Framework?

Entity splitting gives us the ability to take an entity in our model and split this entity into multiple database tables. When we query an entity, Entity Framework will create a query that Automatically joins the related physical tables for us.

11. LINQ to SQL Vs Entity Framework?

Entity Framework:
Work with any database including SQL Server, Oracle, MySQL, DB2 etc.
Entity Framework works well in enterprise scenarios where requirement is to develop a loosely coupled application.
Entity Framework maintain a conceptual model that actually maps to storage model using a mapping. So, it’s possible that multiple EF classes map to one table or multiple tables map to one EF class.
Can generate database from model and it’s a key feature.

LINQ to SQL:
Works but limited to SQL Server.
LINQ to SQL is good in rapid application development scenarios but follows a tightly coupled approach.
A LINQ Entity directly maps to one SQL Server table only. In order to maintain a relationship, it generates a .dbml file.
Generate database from model is not possible.


1. What is an ORM?

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.

2. Why should we use an ORM?

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, ORM 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.

3. What is the Entity Framework?

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.

4. What is LINQ to SQL?

“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.

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

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:

- generate a database if it doesn’t exists or
- connect to an existing database.

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

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

7. What is currently the latest version of Entity Framework?

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.

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

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.

9. 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.

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

The main changes are:

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

11. What is a Migrations in Entity Framework?

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.

12. What is DbContext? What patterns are implemented by it?

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.

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

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.

14. How to resolve migrations conflicts?

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

rollback your database to the state before any of the migrations.
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
Now, with a database that is identical to where the other left it, you should re-scaffold the migration.

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

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.

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

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.

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

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.

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

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

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

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.

20. How would you call an stored procedure in a DbContext?

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);

21. What is property annotation method in EF?

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.

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

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; }

Không có nhận xét nào :

Đăng nhận xét