Entity framework interview questions – LINQ and Entity Framework Interview Questions in .NET

Entity framework interview questions: We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on LINQ and Entity Framework

Question 1.
Define LINQ.
Answer:
LINQ (Language Integrated Query Microsoft) is a uniform programming model for any kind of data access. It is also an OR-mapper that helps us to expedite our business object creation process.

LINQ enables you to query and manipulate data independently of data sources. Figure 13.1 shows how the .NET language stands over the LINQ programming model and works in a uniform manner over any kind of data source. It’s like a query language which can query any data source and any transform. LINQ also provides full type safety and compile time checking.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 1

LINQ can serve as a good entity for the middle tier. So it will sit in between the Ul and data access layer.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 2

Figure 13.2 shows a simple sample of LINQ. We have a collection of data ‘ objcountries’ to which LINQ will is making a query with country name can be any data source dataset, datareader,
XML, etc. Figure 13.2 shows how the ‘ Ob j Countries’ can be any can .of data. We then query for the ‘CountryCode’ and loop through the same.

Question 2.
How does LINQ help us from the perspective of business objects?
Answer:
One of the tedious jobs in business objects is parsing and searching object collections. For instance, consider Figure 13.3 where we want to search a country by an ‘ID’ value. Each loop is used through the collection and gets the object. Many may argue how about keeping a key in List or Array. The below example is just a sample. For instance, if you want to search using country code and name, list / collection keys will not work with those multi-value searches.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 3

In other words, using LINQ, we can query business object collections and filter the collection in a single LINQ query.

Question 3.
Can you explain how a basic LINQ Query looks like?
Answer:
Below is a simple LINQ query that selects all customer data from the ‘ Obj Customer’ collection.

from clsCustomer obj in objCustomer select obj

Question 4.
How do we write a LINQ query to search with criteria?
Answer:
We need to put the where clause before the ‘ select’ keyword.

return from clsCustomer Obj in objCustomer where Obj.customerCode == “001 "select Obj;

Question 5.
How can do join using the LINQ query?
Answer:
Below is the LINQ code snippet for creating joins between object collections. In this case, we are creating a join on customers and orders. If you remember the order collection was contained in the customer class.

return from clsCustomer ObjCust in objCustomer
from clsOrder ObjOrder in ObjCust.Orders
select ObjCust;

Question 6.
How can we do a group by using LINQ query?
Answer:
Below is the code snippet which shows how group by query is written using LINQ. You can see we have created first a temp variable, i.e., ‘GroupTemp’ and then we have used the ‘Select’ clause to return the same.

var GroupCustomers = from ObjCust in objCustomer
                       group ObjCust by ObjCust.City into GroupTemp
select new (GroupTemp.Key, GroupTemp);

Question 7.
What are entity classes in LINQ?
Answer:
Entity Glasses are classes that map to the table structure of your data source. Entity classes represent your business model. The class name of entity class map to table name using the ‘Table’ attribute while table column name map to properties of the class.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 4

Question 8.
How can we load the LINQ entity class?
Answer:
The LINQ entity classes are loaded by using DataContext class as shown in Figure 13.5.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 19

Question 9.
How do we define 1-to-many and many-to-1 relationships in LINQ?
Answer:
1-to-many relationships are defined by using EntitySet and many-to-1 is defined by using entity ref. Below is a sample code snippet that shows ‘ clsCustomer’ having many ‘CLS addresses
object.

[Table(Name = "Customer")]
public class clsCustomer
{
       private EntitySet<clsAddresses> _CustomerAddresses;
       [Association(Storage = "_CustomerAddresses", ThisKey="CustomerId", 
       OtherKey = "Customerld")]
       public EntitySet<clsAddresses> Addresses
       {
             set
             {
                 _CustomerAddresses = value;
             }
             get
             {
                 return _CustomerAddresses;
            }
     }
}

If we need to define a one-to-one relationship we need to use the EntityRef attribute as shown in the below code snippet.

public class clsAddresses
{
       . . . .
       . . . .
       private EntityRef<clsPhone> _Phone;
       . . . .
       . . . .
}

Question 10.
How can we call a stored procedure using LINQ?
Answer:
We can use the function attribute as shown in the below code snippet with the stored procedure name.

[Function(Name = "usp_SelectCustomer", IsComposable = false)]
public ISingleResult<clsCustomerEntity> getCustomerAll()
{
IExecuteResult objResult = this.ExecuteMethodCall(this,
(Methodlnfo)(Methodlnfo.GetCurrentMethod()));

Question 11.
How can we insert, update and delete using LINQ?
Answer:
Insert, update and delete operations in LINQ are done by using ‘ insertOnSubm.it’ , ‘DeleteOnSubmit’ and ‘SubmitChanges’.
To add a new record using LINQ below is the code snippet.

DataContext objContext = new DataContext(strConnectionString);
clsCustomerEntity objCustomerData = new clsCustomerEntity();
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerName = txtCustomerName.Text;
objContext.GetTable<clsCustomerEntity>( ).InsertOnSubmit(objCustomerData);
obj Context.SubmitChanges( ) ;

Below is the code for updating a record by LINQ.

clsCustomerEntity objCustomerData =
(clsCustomerEntity)MyQuery.First<clsCustomerEntity>( );
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerMame = txtCustomerName.Text;
objContext.SubmitChanges( );

Below is the code for deleting records using LINQ,

objContext.GetTable<clsCustomerEntity>( ).DeleteOnSubmit(objCustomerData);
objContext. SubmitChanges( );

Question 12.
What are DBML files in LINQ?
Answer:
DBML stands for Database Markup Language which is a XML file, in big projects we will have large number of tables, developing entity classes for those
tables will be very difficult. DBML files help to automate the creation of entity classes by simple drag-and-drop as shown in Figure 13.6.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 5

Question 13.
What is an Entity framework?
Answer:
ADO.NET entity is a QRM (Object Relational Mapping) that creates a higher abstract object model overADO.NET components.
So rather than getting in to dataset, datatabies, command and connection objects as shown in the below code, you work on higher-level domain objects like customers, suppliers, etc.

DataTable table = adoDs.Tables [0];
for (int j = 0; j < table.Rows.Count; j++)
{
      DataRow row = table.Rows[j];
      // Get the values of the fields
      string CustomerName =
     (string)row["Customername"];
      string CustomerCode =
      (string)row["CustomerCode"];
}

Below is the code of entity framework in which we are working on the higher-level domain objects like a customer rather than working with base-level ADO.NET components (like dataset, DataReader, command, connection objects, etc).

foreach (Customer objCust in obj. Customers)
{ }

Question 14.
So what are the benefits of using EF?
Answer:
The main and the only benefit of EF (Entity Framework) it auto-generates code for Model (Middle layer), Data access layer, and mapping code thus reducing a lot of development time.

Question 15.
So what are the different ways of creating these domain/entity objects?
Answer:
Entity objects can be created in two ways from a database structure or by starting from scratch by creating a model (See Figure 13.7).

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 6

Question 16.
What is pluralize and singularize in the Entity framework dialog box?
Answer:
“Pluralize” and “Singuiarize” give meaningful naming conventions to the objects. In simple words it says do you want to represent your objects with the below-naming convention:

  • What does one Customer record mean? “Customer”(singular).
  • A lot of customer records means “Customer’s” ( plural, watch the “S”)

If you select the below check box entity framework generates a naming convention that adheres to plural and singular coding convention.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 7

Question 17.
What is the importance of the EDMX file in entity framework?
Answer:

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 8

EDMX (Entity Data Model XML) is an XML file that contains ail mapping details of how your objects map with SQL table (See Figure 13.9). The EDMX file is further divided into three sections CSDL (Conceptual Schema Definition Language), SSDL (Software Schema Definition Language), and MSL (Mapping Schema Language).

Question 18.
Can you explain CSDL, SSDL and MSL sections in EDMX file?
Answer:
CSDL (Conceptual Schema Definition Language) is the conceptual abstraction which is exposed to the application.
SSDL (Storage Schema Definition Language) defines the mapping with your RDBMS (Relational Database Management System) data structure. MSL (Mapping Schema Language) connects the CSDL and SSDL.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 9

Question 19.
What are T4 templates?
Answer:
T4 (Text Template Transformation Toolkit) is a template-based code generation engine as shown in Figure 13,11. So you can go and write C# code in T4 templates (, tt is the extension) files, and those C# codes are executed to generate the file as written according to C# logic.
For instance the below T4 C# code:

<#@ template language=” C#” #>
Hello <# Write(“Worldl”) #>

Will generate the following C# output:

Hello
World !

Question 20.
So what is the importance of T4 in the Entity framework?
Answer:
T4 files are heart in EF code generation. So the T4 code templates read the EDMX XML file and generate C# behind code. This C# behind code is nothing but your entity and context classes.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 10

If you create a project using Visual Studio 2012, you will see the hierarchy as shown in Figure 13.12 At the top we have the EDMX (Entity Data Model XML) file, followed by the TT or T4 file and then the .cs code file.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 11

Question 21.
How can we read records using entity framework classes?
Answer:
In order to browse through records you can create the object of the context class and inside the context class, you will get the records.
For instance in the below code snippet we are looping through list of Customer object collection. This customer collection is an output given by the context class
“CustomermytextEntities”.

CustomermytestEntities obj = new
CustomermytestEntiti.es () ;
foreach (Customer objCust in obj.Customers)
{ }

Question 22.
How can we add, update and delete using EF?
Answer:
Create the object of your entity class, add it to the data context using add object method and then call save changes method.

CustomermytestEntities obj = new CustomermytestEntities( ) ;
Customer objCust = new Customer( );
objCust.CustomerCode = "1001";
obj.Customers.AddObject(objCust);
obj.SaveChanges( );

If you want to update, select the object, make change to the object and call accept changes.

CustomermytestEntities objContext = new CustomermytestEntities( );
Customer objCustomer = (Customer)objContext.Customers.FirstOrDefault( );
objCustomer.CountryCode = "NEP";
objContext.AcceptAllChanges( );

If you want to delete call the delete object method as shown in the below code snippet.

CustomermytestEntities objContext = new CustomermytestEntities();
Customer objCustomer = (Customer)objContext.Customers.FirstOrDefau.lt( );
objContext.DeleteObj ect(objCustomer);

Question 23.
People say the entity framework runs slow.
Answer:
By default Entity framework has lazy loading behavior. Due to this default behavior, if you are loading a large number of records, and especially if they have foreign key relationships, you can have performance issues.
So you need to be cautious if you really need lazy loading behavior for all scenarios.
So for better performance disable lazy loading when you are loading a large number of records or use stored procedures.

Question 24.
Can you explain lazy loading in a detailed manner?
Answer:
Lazy Loading is a concept where we load objects on demand rather than loading everything in one go.Consider a situation where you have 1 to many relationships between “Customer” and “Address” object. Now let’s say you are browsing the customer data but you do not want address data to be loaded that moment. But the time you start accessing the address object you would like to load address data from the database.

The entity framework has the lazy loading behavior by default enabled. For instance, consider the below code. When we are doing “foreach” on the customer object address object is not loaded. But the time you start doing “for each” on the address collection address object is loaded from SQL (Structured Query Language) Server by firing SQL queries.

So in simple words, if will fire a separate queries for each address record of the customer which is definitely not good for a large number of records.

MyEntities context = new MyEntities();
var Customers = context.Customers.ToList();
foreach (Customercust in Customers) // In this line no address object loaded
{
     foreach(Address add in cust.Addresses){}// Address object is loaded here
}

Question 25.
How can we turn off lazy loading?
Answer:
The opposite of lazy loading is eager loading. In eager loading we load the objects beforehand. So the first thing is we need to disable lazy loading by setting “LazyLoadingEnabled” to false.

context. ContextOptions.LazyLoadingEnabled = false;

So now we have to explicitly tell EF what objects we want to load by using the “include” function. Below is a simple sample code where we tell EF to load customer as well as address objects by using the “include” function.
So now the customer object and the related address objects will be loaded in one query rather than multiple queries.

var employees = context. Customers.Include(“Addresses”). Take(5);

Question 26.
How can we use stored procedures in entity framework?
Answer:
You can use the stored procedure mapping details in EDMX as shown in the Figure 13.13.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 12

Question 27.
What are POCO classes in Entity framework?
Answer:
POCO means Plain Old C# Object. When EDMX creates classes they are cluttered with a lot of entity tags. For instance below is a simple customer class generated using an entity framework. Many times we would like to use simple .NET classes and integrate the same with entity framework.
The entity framework allows the same. In other words you can create a simple .NET class and use the entity context object to load your simple .NET classes.

Below is a simple class generated by EF which is cluttered with lot of EF attributes.

[EdmEntityTypeAttribute
(NamespaceN ame ="CustomermytestModel",
Name="Customer")]
[ Serializable( )]
[DataContractAttribute(IsReference=true)]
public partial class Customer:
EntityObject
{
      #region Factory Method
      /// <summary>
      /// Create a new Customer object.
     /// </suinmary>
    /// <param name="id">Initial value of the Id property.</param>
   /// <param name="customerCode">Initial value of the CustomerCode
  property.</param>
  /// <param name="customername">Initial value of the Customername
  property.</param>
  public static Customer CreateCustomer(global: : System.Int32 id,
  global: : System.String customerCode, global: : System.String
  customername)
  {
         Customer customer = new Customer( );
         customer.Id = id;
         customer.CustomerCode = customerCode;
         customer.Customername = customername;
         return customer;
}
#endregion
#region Primitive Properties

Question 28.
How to implement POCO in entity framework?
Answer:
To implement POCO is a three-step process:

  • Go to the designer and make the code generation strategy to None. This step means that you would be generating the classes with your own hands rather than relying on EF auto code generation.
  • So now that we have stopped the auto generation of code, we need to create the domain classes manually. So add a class file and create the domain classes like the one “Customer” class we have created.
public class Customer
{
      private string _customerName;
      public string CustomerName;
      {
            get { return _customerName; }
            set { _customerName = value; }
      }
      private int _Customerid;
      public int Customerid
      {
           get { return _Customerid; }
           set { _Customerid = value; }
      }
}

Write your Context layer code inheriting from the “ObjectContext”. I his code you can copy paste from the behind code of EF also before disabling auto-generation.

public partial class Testl23Entities: ObjectContext
{
       public Testl23Entities( )
       : base("name=Testl23Entities", "Testl23Entities")
       {
             this.ContextOptions.LazyLoadingEnabled = true;
             OnContextCreated();
       }
       partial void OnContextCreated( ) ;
       public ObjectSet<Customer> Customers
       {
             get
             {
                   if ( (_Customers == null) )
                   {
                         _Customers =
                         base.CreateObj ectSet<Customer>("Customers");
                   }
                   return Customers;
             }
      }
      private ObjectSet<Customer> _Customers;
      public void AddToCustomers(Customer customer)
      {
              base.AddObject("Customers", customer);
      }
}

And finally, you can use the above code in your client as you were using your EF normally.

Test123Entities oContext = new Test123Entities( );
List<Customer> oCustomers = oContext. Customers. ToList<Customer>( );

Question 29.
in POCO classes do we will need EDMX flies?
Answer:
Yes, you will still need EDMX files because the context object reads the EDMX files to do the mapping.

Question 30.
What is the code first approach in entity framework?
Answer:
In the code first approach, we avoid working with the visual designer of entity framework. In other words, the EDMX file is excluded from the solution. So you now have complete control over the context class as well as the entity classes.

Question 31.
What is the difference between POCO, code first, and simple EF approach?
Answer:
All these three approaches define how much control you want on your Entity framework code. The entity framework is an OR-Mapper it generates lot of code, it creates your middle-tier (Entity) and Data access layer (Context).
But a lot of times you want to enjoy the benefits of both the world you want the auto-generation part to minimize your development time and also you want to control the code so that you can maintain code quality.

Below Is the difference table which defines each of the approaches. In the Simple entity framework, everything is auto generated and so you need the EDMX XML file as well. POCO is semi-automatic so you have full control over the entity classes but then the context classes are still generated by the EDMX file.
In code first you have complete control on how you can create the entity and the context classes. Because you are going to manually create these classes you do not have a dependency on the EDMX XML file, below is a simple table which shows the cross comparison.

EDMX Entity Context
Simple entity framework Needed Auto Auto
POCO approach Needed Manual Auto
Code First Not Needed Manual Manual

Question 32.
How can we handle concurrency in Entity framework?
Answer:

Note: Before this question interviewer can ask you about What is concurrency and What is pessimistic 
and optimistic locking. Please do refer ADO.NET Chapter for the same.

In EF concurrency issue is resolved by using optimistic locking. PleasereferADO.NET Chapter for What is optimistic locking and pessimistic locking?. To implement optimistic locking right click on the EDMX designer and set the concurrency mode to “Fixed” as shown in the Figure 13.14.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 13

Now whenever we have concurrency issues you should get an “OptimisticConcurrency Exception” error as shown in Figure 13.15. You can then put a try / catch to handle this situation.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 14

Question 33.
How can we do pessimistic locking in the Entity framework?
Answer:
We cannot do pessimistic locking using the entity framework. You can invoke a stored procedure from entity framework and do pessimistic locking by setting isolation level in the stored procedure. But direct entity framework does not support pessimistic locking.

Question 34.
What are ciientwins and store wins mode in entity framework concurrency?
Answer:
Clientwins and store wins are actions which you would like to take when concurrency happens. In store wins / database wins the data from the server is loaded into your entity objects. Client wins is opposite to storedwins, data from the entity object is saved to the database.
We need to use the “Refresh” method of the entity framework context and provide the “RefreshMode” enum values. Below is a simple code snippet that executes “Clientwins”.

Context. Refresh (System. Data. Objects. RefreshMode. Clientwins, Obj);

Question 35.
What are scalar and navigation properties in the Entity framework?
Answer:

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 15

Scalar is properties whose actual values are contained in the entities. For example, in the above customer entity “Customer name” and “Customer id” are scalar properties. Normally a scalar property will map to a database field.

Navigation Properties heip to navigate from one entity to the other entity. For instance consider the below example in which we have two entities customer and address and one customer has multiple address objects.

Now we would like to have a facility where at any given moment we would like to browse from a given customer object to the addresses collection and from address object to the customer.

If you open the entity designer you would notice “Navigation” Properties as shown in Figure 13.16. The navigation properties are automatically created from the primary and foreign key references.
So now because of those navigation properties we can browse from Customer to Addresses object, look at the below code.

Customer Cust = oContext.Customers.ToList<Customer>()[0];
// From customer are browsing addresses
List<Address> Addresses = Cust.Addresses.ToList<Address>( );

You can also go vice-versa. In other words from the Address object you can reference the Customer object as shown in the below code.

Address myAddress = Addresses[0];
// From address we can browse customer
Customer cus = myAddress.Customer;

Question 36.
What are complex types In the Entity framework?
Answer:
There can be situations where you have common properties across entities. For example, consider Figure 13.17 where we have “Customer” and “Supplier” entities. They have three fields in common “Address 1”, “Address2” and “Phoneno”. These fields have been duplicated both in “Customer” as well as “Supplier” entities.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 16

So to remove these duplicate and redundant fields we can move them, to a common complex type called “Address”. So complex. types group common fields so that they can be reused across entities.

So to create a complex type, select the fields which you want to group in a complex type. Below is Figure 13.18 which shows the same. Once the complex type is created you can then reuse the complex type with other entities as well.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 17

Question 37.
What is the difference between “DbContext” and “ObjectContext”?
Answer:
“DbContext” is a wrapper around “ObjectContext”, it is a simplified version of “ObjectContext” (See Figure 13.19).

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 18

So as a developer you can start with “DbContext” as It is simple to use. When you feel that some of the operation cannot be achieved by “DbContext” you can then access “ObjectContext” from “DbContext” object as shown in the below code:

((|ObjectcontextAdapter)dbContext).ObjectContext

Note: If the interviewer is asking what kind of operations are not supported in “DbContext”, you can excuse by saying do not remember upfront. Wonder why sometimes the interviewer asks API (Application Programming Interface) level questions?

Question 38.
What’s the difference between LINQ to SQL and Entity framework?
Answer:

  • LINQ to SQL is good for rapid development with SQL Server. EF is for enterprise scenarios and works with SQL servers as well as other databases.
  • LINQ maps directly to tables. One LINQ entity class maps to one table. EF has a conceptual model and that conceptual model maps to the storage model via mappings. So one EF class can map to multiple tables or one table can map to multiple classes.
  • LINQ is more targeted towards rapid development while EF is for the enterprise level where the need is to develop the loosely coupled framework.