Quantcast
Channel: Interview Questions – Web Development Tutorial
Viewing all articles
Browse latest Browse all 26

Top 20 Entity Framework Interview Questions – MUST HAVE

$
0
0

This post is about Entity Framework Interview Questions that will explore various features, concepts and FAQs regarding Microsoft Entity Framework. It’s basically a collection of most frequently asked Entity Framework Interview Questions for developers. You can also explore some practical solutions implementing Entity Framework here:

You are working with WebDevTutorial and building an ADO.NET Entity Framework application for a client. You need to validate the conceptual schema definition language (CSDL), store schema definition language (SSDL), and mapping specification language (MSL) files. Which Entity Data Model tool can you use? (Each correct answer presents a complete solution. Choose all that apply.)
  • A. EDM Generator (EdmGen.exe)
  • B. ADO.NET Entity Data Model Designer
  • C. Update Model Wizard
  • D. Entity Data Model Wizard
  • E. All of Above
  • F. None of Above

For a complete online test and Practice Exams on Web Technologies, Click Here.

 Correct Answer: B, D

Entity Framework Interview Questions List

More Entity Framework Interview Questions for beginners and Experienced

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.Microsoft Entity Framework

Microsoft introduced Entity Framework with .NET Framework v3.5 Service Pack 1 supporting basic Object Relational Mapping support but later EF4 was introduced as second version aligning with .NET Framework v4.0.
Back to top

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.

Back to top

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.

Back to top

What is the Nuget Package console command to install Entity Framework, if it’s not there in you project at that time?

Following is the Nuget Package console command to install Entity Framework:

Install-Package EntityFramework -Version 6.1.1Install Entity Framework -Version 6.1.1
Back to top

How to Install Entity Framework via NuGet Package in Visual Studio?

It’s quite simple to install Entity Framework via Nuget for our project in Visual Studio. For example, If I have just created a new project and want to install Entity Framework, below step by step approach will be helpful.

  1. Right click on the project and choose “Manage NuGet Packages…”.Manage NuGet Packages
  2. On Installation page, choose “Browse” Tab from top left and then enter “Entity Framework” in search box below that and click on search icon. It will list down all Entity Framework related results below. Installing Entity FrameworkAs you can see, we have selected Entity Framework and all details (including version, author, License, Date Published etc.) of the selected item are displayed in right area.
  3. In above screenshot, click on Install button. It will ask for a Review Changes going to be done, confirm by clicking “YES”.Review Install EF
  4. It followed by a License Acceptance confirmation. Just confirm by clicking “I Accept”.License Acceptance EF
  5. Once you accept the License, it will complete the installation displaying details in Visual Studio Output Window as shown in below screenshot.Entity Framework Installed Finally, you can see the successful installation message in Output Window. Once the installation is done successfully, you can see EntityFramework and EntityFramework.SqlServer in References of our project.

Back to top

Where do we use Virtual classes in Entity Framework DbContext Models?

We use Virtual classes in Entity Framework in context class where we define DBSet of corresponding table. As we can see easily in below code sample for Students and Departments:
Entity Framework Interview Questions Virtual Classes
Back to top

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.
Back to top

What’s new in Entity Framework 6?

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

Whats New In EF6

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).
Back to top

Can we access a model in Entity Framework without primary key defined?

No, but we can access data.

Using Primary Key:

Student student = db.Students.Find(id);

Without Primary Key:

Student student = db.Students.Where(x=>x.StudentName==”Ahmad”);

Back to top

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.

Student student = db.Students.Find(id); //----> Step 1: Student record will load.
if(student != null){
	student.Department; // ---> Step 2: Department details will be loaded.
}

Note: As by default, lazy loading option is enabled in Entity Framework but that can cause major performance issues in some scenarios as below:

var students = db.Students.ToList(); // no department will be loaded.
foreach(var student in students)
{
	student.Department; //department will be loaded here.
}

As for above scenario, student.Department will load department from SQL Server by firing a new SQL query for each iteration and it’s a performance degradation in case of large number of records.
We can disable Lazy loading (or in other words, enable eager loading) by using the following code:

db.ContextOptions.LazyLoadingEnabled = false;

Back to top

Why DB Context models object disposal is important in Entity Framework?

Until it’s disposed, it will be holding resources that aren’t in. If not disposed then Garbage collector will free the space but in some instance it holds up.

Calling dispose method to clear memory.Dispose in Entity Framework
Back to top

Can we do an insertion and deletion at the same block of code and then Apply save changes to them in a statement in Entity Framework?

Yes, WE CAN by using the below piece of code:

Save changes in Entity Framework

Here the student record will insert to db but not physically. When we call SaveChanges method then it actually insert in db and commit the transaction. If we delete before committing transaction nothing will change in database.
Back to top

What are the development approaches are supported in Entity Framework?

Following are the development approaches available in Entity Framework. Implementation of each approach is given in detail in separate Entity Framework Tutorial:

  • Code First Approach – where code defines the database. Entity Framework handles creation. A complete detailed implementation of Entity Framework Code First Approach here.
  • Database First Approach – regular approach used where database is first created or already exists.
  • Model First Approach – where model is drawn first that further generate database scripts.

Development Approaches in Entity Framework
Back to top

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

An important point to remember about EF Code First approach; we have to follow proper convention for a primary key, means Entity Framework expects ID combined with Entity Name. In our case, above referred Code First Example, we have two entities (i.e. Category and Product) and for both of these entities, we used proper convention for primary key i.e. CategoryId and ProductId.

But in case we used something different i.e. “UniqueCategoryIdentifier” or “UniqueProductIdentifier”, then we have to tell that this is our primary key column and this can be done using a simple attribute i.e. “Key” as follows:

public class Category
{
   [Key] 
   public int UniqueCategoryIdentifier { get; set; }

   public string CategoryName { get; set; }

   public ICollection<Product> Products { get; set; }
}

public class Product
{
   [Key]
   public int UniqueProductIdentifier { get; set; }

   public string ProductName { get; set; }

   public decimal Price { get; set; }

   ....
   ....
}

If we don’t follow the convention as well as not using the “Key” attribute, then will end up with following error.

"One or more validation errors were detected during model generation: System.Data.Edm.EdmEntityType : EntityType 'Category' has no key defined. Define the key for this Entity Type........"

Note: It’s always recommended to use proper convention or use “Key” attribute to tell Entity Framework about our primary key field.

Back to top

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. For example, If we want to have minimum and maximum number of limit for CategoryName field for Category Entity (say minimum 10 and maximum 100 characters). Below is the way to use, MinLength and MaxLength:

public class Category
{
   [Key] 
   public int UniqueCategoryIdentifier { get; set; }
 
   [MaxLength(100, ErrorMessage="Maximum of 100 characters allowed")]
   [MinLength(10, ErrorMessage="Minimum of 10 characters required")]
   public string CategoryName { get; set; }
 
   public ICollection<Product> Products { get; set; }
}

Back to top

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.

Let’s take a practical example, we have an entity i.e. Product and we want to have a ProductCode that will not be mapped to database. So, we will do the following to achieve in Code First Approach.

public class Product
{
   [Key]
   public int UniqueProductIdentifier { get; set; }
 
   public string ProductName { get; set; }

   [NotMapped]
   public string ProductCode 
   {
	get{
		return UniqueProductIdentifier + "-" + ProductName
	}
   }
 
   public decimal Price { get; set; }
 
   ....
   ....
}

Back to top

What is the query syntax we use to query an ADO.NET Entity Data Model?

We can use LINQ to Query ADO.Net Entity Framework. For Example:

Entity Data Model
Back to top

Is LINQ a feature of Entity Framework?

Yes, following is the example to get student record from Section A.

LINQ feature in EF6

The same in Entity Framework:

Student student = db.Students.Where(x=>x.Section==”A”);
Back to top

Does Default New Project Creation under Internet Template Category of ASP.NET MVC have any DB Context Ready while creating the project?

Yes, There is, as we can see in the below screenshot:Template Category For MVC
Back to top

If you provide the Primary Key value while inserting record to Entity Framework, will that execute fine, or will it throw an error while the adding statement?

Yes it will threw error if same a record present with same data. If identity is set then it will give error in any case.Insert In EF6
Back to top

What are the properties or Database Elements get copied in Dataset when Clone method is used?

It will create a new object with same properties with a new instance.Clone Method in EF6
Back to top

What is the role of a Self-Tracking Entities?

Self-tracking entity allows you to add code generated item:Self Tracking Entities in EF6
Back to top

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.
Back to top

What is the role of Entity Container in Entity Framework?

Entity container is a logical grouping of entity sets, association sets, and function imports.  The following must be true of an entity container defined in a conceptual model:

At least one entity container must be defined in each conceptual model.  The entity container must have a unique name within each conceptual model.

Entity Container in EF
Back to top

Do we need to define any assembly references of entity framework if we use in web.config file?

Yes, that is necessary:web.config for Entity Framework

Back to top

More Entity Framework Interview Questions including Entity Framework Core

LINQ to SQL Vs Entity Framework?

Following table clearly explains the difference between LINQ to SQL Vs Entity Framework:

Entity Framework LINQ to SQL
Work with any database including SQL Server, Oracle, MySQL, DB2 etc. Works but limited to SQL Server.
Entity Framework works well in enterprise scenarios where requirement is to develop a loosely coupled application. LINQ to SQL is good in rapid application development scenarios but follows a tightly coupled approach.
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. A LINQ Entity directly maps to one SQL Server table only. In order to maintain a relationship, it generates a .dbml file.
Can generate database from model and it’s a key feature. Generate database from model is not possible.
Back to top

How to handle transactions in Entity Framework 6

Transaction being a single unit of work that are either successful or failed has really important for an application that is developed using Entity Framework. Entity Framework supports transactions in following ways and this Entity Framework 6 Interview Questions demonstrate the same:

The “SaveChanges()” method in Entity Framework operates within a transaction and saves results of the work. This is how the data integrity is being ensured.

In Entity Framework 6.0, two new APIs are used to maintain the transaction:

1. DbContext.Database.BeginTransaction: Below we can find source code to understand that how different operations are combined within the same transaction and further are all committed or rollbacked. This method also allows us to specify the isolation level for the transaction.

using (EFModelFirst_DemoContainer context = new EFModelFirst_DemoContainer()) 
{ 
      using (var transaction = context.Database.BeginTransaction()) 
      try 
      { 
            Category c = new Category(); 
            c.CategoryName = "Mobile"; 
            context.Categories.Add(c); 
            context.SaveChanges();

            Product p = new Product(); 
            p.CategoryId = c.CategoryId; 
            p.ProductName = "HTC"; 
            p.Price = "15000"; 
            context.Products.Add(p); 
            context.SaveChanges();
  
            transaction.Commit(); 
       }
       catch (Exception ex) 
       { 
            transaction.Rollback(); 
       } 
}

2. DbContext.Database.UseTransaction: It allows DbContext to use a transaction that was stated outside of the Entity Framework. It means using this API we can use any existing transaction with Entity Framework.

It is used when sometimes we must use an existing transaction that is started outside of the Entity Framework.

public EFModelFirst_DemoContainer() 
: base("name=EFModelFirst_DemoContainer") 
{
}
(SqlConnection con = new SqlConnection("connectionString")) 
  { 
     con.Open(); 
     using (var transaction = con.BeginTransaction()) 
     { 
         using (var transaction1 = context.Database.BeginTransaction()) { 
           try 
           {  
               Category c = new Category(); 
               c.CategoryName = "Mobile"; 
               context.Categories.Add(c); 
               context.SaveChanges();

               Product p = new Product(); 
               p.CategoryId = c.CategoryId; 
               p.ProductName = "HTC"; 
               p.Price = "15000"; 
               context.Products.Add(p); 

               context.SaveChanges();
               transaction.Commit(); 
            }
            catch (Exception ex) 
            { 
               transaction.Rollback(); 
            }
       } 
  }

Back to top

  • Learn ASP NET MVC 5 step by step [Maruti Makwana, Corporate Trainer] 28 Lectures, 2.5 Hours Video, Intermediate Level
    Very easy to learn video series on Asp.Net MVC 5 Specially for those who are familiar with Asp.Net Web forms.
  • AngularJS for ASP.NET MVC Developers [Brett Romero] 10 Lectures, 1 hour video, Intermediate Level
    The Fastest Way For .NET Developers To Add AngularJS To Their Resume
  • ASP.NET with Entity Framework from Scratch [Manzoor Ahmad, MCPD | MCT] 77 Lectures, 10 hour video, All Level
    Latest approach of web application development
  • Comprehensive ASP.NET MVC [3D BUZZ] 34 lectures, 14 Hours Video, All Levels
    From zero knowledge of ASP.NET to deploying a complete project to production.

Concluding Notes:

Again, this is my prepared list of important Entity Framework Interview Questions but reader can suggest/contribute more related concept area. I’ll be more happy to add those questions/concepts and update the Entity Framework Interview Questions list.

More Related Articles:

Top Web Developer Interview Questions and Answers Series:

ASP.NET MVC Jobs [Updated Daily]

Top ASP.NET MVC Jobs

Developer Lead - ASP.NET, C#
Source: Excell
Details: MVC). ASP.NET MVC, C#, WebAPI. As part of a leading IT managed services specialist with more than 12,000 associates worldwide, we rely on the personal...  More
1 day ago

Redmond, WA 98052 10-May-2017

Sr .NET Developer / Moible Development (Conyers)
Source: Synergy Hire LLC
Details: MVC. In this role you will be working on both front-end and back-end web development utilizing C#, ASP.Net MVC, Entity Framework and SQL Server on the server...  More
9 days ago

Conyers, GA 01-May-2017

Lead .Net & Mobile Developer
Source: Posh Technologies
Details: Visual Studio 2013+, C#, ASP.NET MVC 5 and Web API 2. 5+ years of working experience with C#, ASP.Net MVC, SQL Server, JavaScript....  More
6 days ago

Redmond, WA 04-May-2017

Lead .NET Developer with Public sector
Source: Indeed
Details: Hi Hope you doing great. Please find the below requirement, if you are comfortable with the below requirement send me your updated resume ASAP. *Job Title:...  More
1 day ago

Harrisburg, PA 09-May-2017

Sr Lead .Net Developer
Source: Indeed
Details: *Direct Client Requirement* *VISA copy, DL Copy and Passport Number (OR) Passport Copy Needed.* *Job Title: Sr Lead .Net Developer* *Location: * *Harrisburg...  More
2 days ago

Harrisburg, PA 08-May-2017

contract Sr .NET Developer
Source: Indeed
Details: ASP.NET or ASP.NET MVC:. 5-7 years of proven experience using Microsoft technologies including ASP.NET and ASP.NET MVC, IIS8, Azure, and SQL Server;...  More
2 days ago

Irvine, CA 92606 08-May-2017

Mid level .Net Developer
Source: Indeed
Details: IT Solutions Consulting, a full-service consulting firm in Fort Washington, PA, needs a mid-level ASP.NET software developer for a full-time position at our  More
8 days ago

Fort Washington, PA 19034 02-May-2017

Mid Level C#/ASP.Net Developer
Source: Indeed
Details: 2+ years' experience with ASP.NET MVC, at least 1 year using the 4-4.5 framework. Ideal candidate will have 2-5 years of web-based application development and...  More
12 days ago

Nashville, TN 28-April-2017

Software Engineer .NET, C#
Source: American College of Healthcare Executives
Details: Utilize ACHE’s evolving technology stack including Visual Studio, C#, MS SQL Server, ASP.NET, MVC, XML/XSLT, JavaScript, and jQuery....  More
15 days ago

Chicago, IL 60606 26-April-2017

Lead .Net Developer
Source: conrep
Details: Object Oriented Programming, WCF, VB.Net, Visual Studio 2008, Enterprise Library, MSMQ, Security Fundamentals, SSIS, SSRS, ASP.NET, MVC 4.0, HTML, SQL 2008 or...  More
1 day ago

Dimondale, MI 48821 09-May-2017

Lead .Net Developer
Source: Indeed
Details: MVC 4.0 or higher .NET technologies and Framework - 3Years. Object Oriented Programming, WCF, VB.Net, Visual Studio 2008, Enterprise Library, MSMQ, Security...  More
1 day ago

Lansing, MI 09-May-2017

Sr Lead .Net Developer
Source: Indeed
Details: ASP.NET MVC - 5 Years. The ideal candidate would have experience with Microsoft Test Manager or other similar testing tools, and be responsible for writing unit...  More
3 days ago

Harrisburg, PA 08-May-2017

Software Engineer C#/ASP.NET MVC/JavaScript
Source: Cormant, Inc.
Details: You will be working on full stack development including Marionette client, and a C# MVC architecture with NHibernate/RDBMS as the back-end....  More
19 days ago

San Luis Obispo, CA 21-April-2017

Junior to Mid-level .Net Developer
Source: Indeed
Details: Experience with the MVC pattern for web development. US Citizens or Greencard that do not require a Visa Sponsorhip for Full-Time Employment*....  More
22 days ago

Englewood, CO 18-April-2017

Lead .Net Developer
Source: Indeed
Details: Previous experience with the .NET Framework, C#, ASP.NET MVC, and SQL Server. Required 3+ years’ experience in development with experience using the .NET...  More
11 days ago

San Juan, PR 30-April-2017

Web Developer (.NET)
Source: Indeed
Details: ASP.NET, MVC, MS SQL Server, JQuery and Object Oriented Design concepts. Design, develop, and implement data-driven Microsoft ASP.NET web applications for EA...  More
23 days ago

Hunt Valley, MD 17-April-2017

Sr. C#.NET Developer / Lead
Source: TechPeople
Details: Experience in Web application development with ASP.NET, MVC, HTML, JavaScript, CSS, and AJAX. Sr....  More
14 days ago

Houston, TX 26-April-2017

.NET Application Developer - Lead
Source: 2rbConsulting
Details: Experience with ASP.NET MVC and Web Forms. 2rbConsulting is seeking an experienced Lead .NET Application Developer, working with a Product Development &...  More
14 days ago

Rancho Cordova, CA 26-April-2017

Houston, Texas .NET Developer
Source: Indeed
Details: Experience with .NET Framework components such as ASP.NET MVC, MSSQL, Web Services, and OOP concepts. Seeking an experienced .NET developer with a strong...  More
28 days ago

Houston, TX 13-April-2017

Senior/Lead .Net Application Developer
Source: SunTrust
Details: Senior/Lead .Net Application Developer-W428880 Description The successful candidate is a technical individual who has a passion for delivering high quality  More
18 days ago

San Diego, CA 22-April-2017

.NET Developer, Senior Level
Source: Nexient
Details: Experience with modern frameworks – MVC and bootstrap at a minimum. Strong experience in object oriented design & development, Design Patterns, Multi-threading,...  More
30+ days ago

Nashville, TN 07-April-2017

.NET/C# Software Integration Engineer
Source: BlueVolt
Details: Solid programming experience with C#, WCF, Restful services using WEB API, and ASP.NET MVC. BlueVolt is growing....  More
13 days ago

Portland, OR 27-April-2017

.NET Developer
Source: Skills Provision Ltd
Details: O ASP.NET MVC 4+. O Telerik UI for ASP.Net MVC. Are you ready for your next challenge?...  More
6 days ago

Houston, TX 04-May-2017

C# .Net Developer
Source: Indeed
Details: Location: *Modesto, CA* Duration: *1 Years* *Senior C#.Net Developer* *Face to Face Interview required* Job Summary * Under the general supervision of the  More
7 days ago

Modesto, CA 03-May-2017

C# .Net Developer
Source: Indeed
Details: Experience with multiple program languages specifically C#, ASP.NET, JavaScript, Angular, ASP.NET MVC....  More
9 days ago

Raleigh, NC 01-May-2017

The post Top 20 Entity Framework Interview Questions – MUST HAVE appeared first on Web Development Tutorial.


Viewing all articles
Browse latest Browse all 26

Trending Articles