Entity Framework Interview Questions With Answers
Entity Framework Interview Questions With Answers
Contents
What is Entity framework? ..................................................................................................... 3 So what are benefits of using EF?........................................................................................... 3 So what are the different ways of creating these domain / entity objects? ............................. 3 What is pluralize and singularize in Entity framework dialog box? ....................................... 4 What is the importance of EDMX file in entity framework? ................................................. 5 Can you explain CSDL, SSDL and MSL section in EDMX file? .......................................... 5 What are T4 templates? .......................................................................................................... 5 So what is the importance of T4 in Entity framework? .......................................................... 6 How can we read records using entity framework classes? .................................................... 6 How can we add, update and delete using EF? ....................................................................... 7 People say entity framework runs slow? ................................................................................ 7 Can you explain lazy loading in a detailed manner ? ............................................................. 8 How can we turn off lazy loading? ......................................................................................... 8 How can we use stored procedures in entity frame work? ..................................................... 9 What are POCO classes in Entity framework? ....................................................................... 9 How to implement POCO in entity framework? .................................................................. 10 In POCO classes do we will need EDMX files?................................................................... 12 What is code first approach in entity framework? ................................................................ 12 What is the difference between POCO, code first and simple EF approach? ....................... 12 How can we handle concurrency in Entity framework? ....................................................... 13 How can we do pessimistic locking in Entity framework?................................................... 13 What is client wins and store wins mode in entity framework concurrency? ...................... 14 What are scalar and navigation properties in Entity framework? ......................................... 14 What are complex types in Entity framework?..................................................................... 15 Whats the difference between LINQ to SQL and Entity framework? ................................ 16
// 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 customer rather than working with base level ADO.NET components( like dataset , datareader , command , connection objects etc).
foreach (Customer objCust in obj.Customers) {}
So what are the different ways of creating these domain / entity objects?
Entity objects can be created by two ways from a database structure or by starting from scratch by creating a model.
EDMX (Entity Data Model XML) is a XML file which contains all mapping details of how your objects map with SQL tables. The EDMX file is further divided in to three section CSDL , SSDL and MSL.
Can you explain CSDL, SSDL and MSL section in 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.
If you create a project using VS 2012, you will see the following hierarchy. At the top we have the EDMX file, followed by the TT or T4 file and then the .CS code file.
For instance in the below code snippet we are looping through list of customer object collection. This customer collection is a output given by the context class CustomermytextEntities.
CustomermytestEntities obj = new CustomermytestEntities(); foreach (Customer objCust in obj.Customers) {}
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.FirstOrDefault(); objContext.DeleteObject(objCustomer);
You can see this youtube.com video which shows a simple insert,update and delete example using entity framework http://www.youtube.com/watch?v=b6vTIiBNcJ0
So for better performance disable lazy loading when you are loading large number of records or use stored procedures.
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);
/// <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; }
Write your Context layer code inheriting from the ObjectContext. This code you can copy paste from the behind code of EF also before disabling autogeneration.
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 you can use the above code in your client as you where using your EF normally.
Test123Entities oContext = new Test123Entities(); List<Customer> oCustomers = oContext.Customers.ToList<Customer>();
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 frame work code. Entity framework is an OR MAPPER it generates lot of code, it creates your middle tier (Entity) and Data access layer (Context). But lot of times you want to enjoy benefits of both the world you want the auto-generation part to minimize your development time and also you want control on the code so that you 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 you need the EDMX XML file as well. POCO is semi-automatic so you 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 the 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.
Code First
Not Needed
Manual
Manual
In EF concurrency issue is resolved by using optimistic locking. Please refer ADO.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 below figure.
Now whenever we have concurrency issues you should get OptimisticConcurrencyException error as shown in the below figure. You can then put a try / catch to handle this situation.
We cannot do pessimistic locking using entity framework. You can invoke a stored procedure from entity framework and do pessimistic locking by setting isolation level in the stored procedure. But directly entity framework does not support pessimistic locking.
What is client wins and store wins mode in entity framework concurrency?
Client wins 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 in to your entity objects. Client wins is opposite to stored wins, 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 which executes ClientWins.
Context.Refresh(System.Data.Objects.RefreshMode.ClientWins,Obj);
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];
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];
So to create a complex type, select the fields which you want to group in a complex type, click on refactor and create the complex type. Below is the figure which shows the same. Once the complex type is created you can then reuse the complex type with other entities as well.
Please do visit my site www.questpond.com which has lot of videos on C#,.NET,EF,MVC,Design pattern etc.