1) What is the advantage and disadvantage of Entity Framework
Advantages:
One common syntax (LINQ) for all object queries whether it is database or not , Pretty fast if used as intended , easy to implement SoC , less coding required to accomplish complex tasks.
Its fast and straight forward using LINQ/FE objects For Add/Modify/Delete/Update.
Easy to map business objects (with drag & drop tables on environment). It keeps a good performance when work with a small / middle domain model.
Disadvantages:
we have to think in a non-traditional way of handling data , not available for every database.
If there is any schema change in database FE won’t work. We have to update the schema in solution as well!!!
It’s limited when we work with a huge domain model. -Scalability.
2) When should use EF and when we should not use EF.
EF can’t handle more if number of datatable roughly maximum 250. whenever, if we have more than 250 tables, e.g. 1000+, I think break up 1000+ tables into several logical groups of tables, and use one EF model per such logical group (with up to 250 tables in it). If we do not want to have several model in a project, then 1000+ tables in one model is not so good.
3) What would be the performance of the EF when we do huge data fetching or updating or inserting etc.
- EF performs slower when it has to populate an Entity with deep hierarchy. Be extremely careful with entities with deep hierarchy
- Indexing of database is good but in case of EF it becomes very important. The columns use for retrieval and sorting should be properly indexed.
- When the model is large, VS2010/VS2012 Model designer gets real crazy. so break the model into medium sized models. There is a limitation that the Entities from different models cannot be shared even though they may be pointing to the same table in the database.
- Transactions are slow. be careful with them
4) Why should not use Entity Framework or an ORM?
- Bulk updates (in addition to bulk inserts)
- Querying across multiple databases: EF currently restricts the entities in a single context to a single database. If you are forced to work with a multi-database setup, this could be an issue.
- Lack of support for nullable keys: if you are dealing with a legacy data model where some tables have unique clustered indices with nullable columns, you will find EF unable to deal with this
5)What is the importance of EDMX file in Entity Framework?
EDMX (Entity Data Model XML) is an XML file which contains all the mapping details of how the objects map with SQL tables. The EDMX file is further divided into three sections: CSDL, SSDL, and MSL.
6)Explain CSDL, SSDL and MSL sections in an EDMX file?
- 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 data structure.
- MSL (Mapping Schema Language) connects the CSDL and SSDL.
CSDL, SSDL and MSL are actually XML files.
7) What are T4 templates?
T4 (Text Template Transformation Toolkit) is a template based code generation engine. To write C# code in T4 templates (.tt is the extension) files and those C# codes execute to generate the file as per the written C# logic.
For instance, the below T4 C# code:
<#@ template language=”“C#”” #>
Hello <# Write(”World!”) #>
Will generate the following C# output:
Hello
World !
Importance Of T4
It is EF code generation. The t4 code templates read the Edmx file and generate c# code behind. The c# code
8)How to read records using Entity framework?
We create the object of context class and inside this context class will get the records.
Ex—customercontext custe=new customercontext();
Foreach(cusromer objcust in custe.customers){}
9)People say Entity Framework runs slow
By default EF has lazy loading behavior. Due to this default behavior if we are loading a large number of records and especially if they have foreign key relationships, we can have performance issues. So we need to be cautious if really need lazy loading behavior for all scenarios. For better performance, disable lazy loading when we are loading a large number of records or use stored procedures.
10)Can you explain lazy loading in a detailed manner?
Lazy loading is a concept where we load objects on demand rather than loading everything in one go. Consider a situation where we have 1 to many relationships between the Customer and Address objects. Now let’s say we are browsing the customer data but we do not want address data to be loaded at that moment. But the time we start accessing the address object we would like to load address data from the database.
Entity Framework has lazy loading behavior by default enabled. For instance, consider the below code. When we are doing a foreach on the Customer object, the Address object is not loaded. But the time we start doing foreach on the address collection, the Address object is loaded from SQL Server by firing SQL queries.
So in simple words, it will fire a separate query 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
}
11)How can we turn off lazy loading?
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;
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.
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);
12)What are POCO classes in Entity Framework?
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 Entity Framework. Many times we would like to use simple .NET classes and integrate them with Entity Framework.
Entity Framework allows this. 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 a lot of EF attributes.
[EdmEntityTypeAttribute(NamespaceName=”CustomermytestModel”, Name=”Customer”)]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Customer : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new Customer object.
/// </summary>
/// <param name=”id” />Initial value of the Id property.
/// <param name=”customerCode” />Initial value of the CustomerCode property.
/// <param name=”customername” />Initial value of the Customername property.
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
13)How do we implement POCO in Entity Framework?
To implement POCO is a three step process:
Go to the designer and set the code generation strategy to NONE. This step means that we would be generating the classes on own rather than relying on EF auto code generation.
Now that we have stopped the auto generation of code, we need to create the domain classes manually. Add a class file and create the domain classes like the Customer class we 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
ObjectContext. Disable auto-generation.
public partial class Test123Entities : ObjectContext
{
public Test123Entities()
: base(“name=Test123Entities”, “Test123Entities”)
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
partial void OnContextCreated();
public ObjectSet<Customer> Customers
{
get
{
if ((_Customers == null))
{
_Customers = base.CreateObjectSet<Customer>(“Customers”);
}
return _Customers;
}
}
private ObjectSet<Customer> _Customers;
public void AddToCustomers(Customer customer)
{
base.AddObject(“Customers”, customer);
}
}
And finally we can use the above code in client as if where using EF normally.
Test123Entities oContext = new Test123Entities();
List<Customer> oCustomers = oContext.Customers.ToList<Customer>();
14)In POCO classes do we need EDMX files?
Yes, still need EDMX files because the context object reads the EDMX files to do the mapping.
15)What is Code First approach in Entity Framework?
In 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 now have complete control over the context class as well as the entity classes.
16)What is the difference between POCO, Code First, and simple EF approach?
All these three approaches define how much control you want on your Entity Framework code. Entity Framework is an OR mapper, it generates a lot of code, it creates middle tier (Entity), and Data Access layer (Context).
But a lot of times we want to enjoy the benefits of both worlds, we want the auto-generation part to minimize development time and also want control on the code so that we can maintain code quality.
Below is the difference table which defines each of the approaches. In simple Entity Framework, everything is auto generated and so we need the EDMX XML file as well. POCO is semi-automatic so we have full control on 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 context classes. Because you are going to manually create these classes, you do not have 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 |
17)What is the difference between DbContext and ObjectContext?
DbContext is a wrapper around ObjectContext, it’s a simplified version of ObjectContext.

As a developer you can start with DbContext as it’s simple to use. When you feel that some of the operations cannot be achieved by DbContext, you can then access ObjectContext from DbContext, as shown in the below code:
((IObjectContextAdapter)dbContext).ObjectContext
18) 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, we can pull data and query it using language similar to SQL.
19) How is data retrieved?
The difference between older retrieval methods and current Entity framework retrieval methods is that we can now (with Entity) retrieve data as objects. The objects represent the tables (or linked tables) in database. Instead of iterating through several columns and rows, you just use your class data models. For instance, if we have a table named “users,” we can use the “users” class instead of working through each data set after your query.
20) Can we run SQL statements in an Entity framework environment?
Yes, we can also run SQL query statements. 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. we can also run stored procedures from a database.
21) How do you create a database model?
Visual Studio has a database modeler available. we can create a database model from scratch, or we can query the database for the models. If we have a database already, you simply pull the database structures from your code and Entity framework will automatically set up the class data models.
22) Does Entity framework support primary and foreign keys?
Yes, Entity framework supports both types of primary and foreign keys. we can define these in the database tables and import them to your model classes. If don’t already have a database set up, we can create these keys in the data model classes and their respective data modeling classes.
23) How do you mark a data column as required by the database?
we can “decorate” the 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. we can also auto-generate required fields in the code, so the code automatically adds the required data.
24) What is lazy loading?
Lazy loading is a way to return only objects that are used. When we query from 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 we can reserve memory and storage when work with large programs. It also means that objects are created until need them, so it makes your program faster.
25) What is eager loading?
Eager loading is the opposite of lazy loading. When we query for objects, eager loading returns all of the objects including the related objects. For instance, when we 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).
26) What is a navigation property?
A navigation property points to related tables in the database model. For instance, if we 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 we view the Entity framework model, we can view the navigation properties to better understand the structure of your tables.
27) 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.
28) What is a complex data type?
A complex data type occurs when we need to point to another data object from one data object. For instance, if we have several tables that require an address, we can turn those addresses into a table of addresses. then point the 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.
29) Overall, what is Entity framework?
Entity framework is a type of ORM (object relationship model) 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 query databases using LINQ, and we do not need to worry about the database connection. Additionally, we 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. Entity framework is a comprehensive tool when we want to work with databases in your .NET development platform.
30)Difference between ObjectContext and DbContext
ObjectContext
ObjectContext is a class that manages all the database operations, like database connection, and manages various entities of the Entity Model. We can say that ObjectContext is the primary class for accessing or working together with entities that are defined in the conceptual model.
DbContext
DbContext is conceptually similar to ObjectContext. DbContext is nothing but a ObjectContext wrapper, we can say it is a lightweight alternative to the ObjectContext. DbContext can be used for DataBase first, code first and model first development. DbContext mainly contains a set of APIs that are very easy to use. The API is exposed by ObjectContext. These APIs also allow us to use a Code First approach that ObjectContext does not allow.
ObjectContext VS DbContext
| ObjectContext | DbContext |
| ObjectContext class is part of the core Entity Framework API, that allows us to perform queries, change and track updates of the Database by using strongly typed entity classes. | The DbContext class can be described as a wrapper of ObjectContext. It exposes the most commonly used features of ObjectContext. |
| ObjectContext supports Compiled Queries. | DbContext does not support Compiled Queries. |
| ObjectContext supports self-tracking of Entities | DbContext does not support self-tracking of Entities. |
| ObjectContext is only useful in Model First and Database First approaches | DbContext is useful in Model First, Database First approach as well as Code First approach. |
| ObjectContext can be used by Entity Framework 4.0 and below. | DBContext can be used by Entity Framework 4.1 and above. |
| The ObjectContext class is not thread-safe. | Any public static (C#) or Shared (Visual Basic) members of DbContext are thread-safe. Any instance members are not guaranteed to be thread safe. |
There are also many methods in common in both ObjectContext and DbContext. For example ObjectContext has a direct method to execute a query against a database whereas the DbContext.DataBase class contains the SQLQuery method to obtain the same result.
Example
// using ObjectContext (EF4.0)
using (Entities context = new Entities())
{
IEnumerable<EmployeeDetails> empDetails = context.ExecuteStoreQuery<EmployeeDetails>
(“exec GetEmployeeData”).ToList();
}
// using DBContext (EF 4.1 and above)
using (Entities context = new Entities())
{
IEnumerable<EmployeeDetails> empDetails = context. Database.SqlQuery
< EmployeeDetails >(“exec GetEmployeeData “, null).ToList();
}
DbContext also has some sets of methods that are not available with ObjectContext, like Dbset.Find, DbSet.Local etcetera.
Some of the ObjectContext methods are also renamed. For example ObjectContext has methods like AddObject, DeleteObject And Attech on ObjectSet<T>, in DbContext, they are named Add, Remove and Attach on DbSet<TEntity>.


