Ultimate list of entity framework interview questions

Facebook
Twitter
LinkedIn

Never miss a post!

Sign up for our newsletter and get FREE Development Trends delivered directly to your inbox.

You can unsubscribe any time. Terms & Conditions.
Categories

Entity Framework is one of the ORM (Object Relational Mapping) tools. If we say what ORM is: It is the tool that acts as a bridge between the relational database and object oriented programming (OOP). This bridge is a structure where we use our object models to manage our information in the relational database. In short, it is a framework developed by Microsoft that connects our objects to the database and exchanges data for us. Anyone without SQL knowledge can perform database operations with EF. There is no dependency on any database. Oracle can be used with MS SQL. Entity framework is used in many projects today. That’s why .Net developers should definitely be familiar with the details.

What is DbContext entity framework?

Context class is generally the class in which database operations are handled. Context class derives from DbContext class and is a very important class for Entitiy Framework. Example usage is as follows;

public class SchoolContext : DbContext 
{ 
    public SchoolContext() { } 
    public DbSet<Student> Students { get; set; } 
    public DbSet<StudentAddress> StudentAddresses { get; set; } 
    public DbSet<Grade> Grades { get; set; } 
}  

The SchoolContext class is derived from the DbContext class, which makes it the Context class. This class includes 3 entities (Students, StudentAdresses, Grade).
All of these entities correspond to a table on the database. With the configuration methods on DbContext, you can make all the configurations you use while creating the tables in the database, such as the relationships on these entities, the table to be mapped, field types, and lengths. Besides, you can specify your database connection clause via DbContext.

DbContext is where database operations are fully controlled. After completing the database operations, you can override the method you will use to save your changes (delete, update, add). Through this method, perhaps you may want to write the information on which fields have changed in a separate table.In this way, you can keep the change history in your database.

What is lazy loading in Entity Framework?

Lazy Loading works with the principle that an item on the page is not called if it is not needed, that is, it is used to not receive and hold an object instance until it is actually needed. In this method, data is pulled depending on the query and instead of loading all the data in the data set, it queries again and pulls the data when used.

For example, when we run the query given below, the UserDetails table will not be loaded with the Users table.

User usr = dbContext.Users.FirstOrDefault (a => a.UserId == userId);

It will only load when you search explicitly, as shown below.

UserDeatils ud = usr.UserDetails; // UserDetails are loaded here

This means a query is sent to the database for each new installation. In fact, in case you do not need user details, this will provide an increase in performance. However, when you need and want to access user details, the upper class it depends on is added to the query again and pulled again. This is a negative situation in terms of performance. In case you absolutely need details, it would be beneficial not to turn this feature off. The lazy loading feature on the Entity framework comes on by default. You can turn this feature off with the following code.

dbContext.Configuration.LazyLoadingEnabled = false;

What is eager Loading ?

It works in the opposite direction to Lazy Loading. It creates and holds the objects we will use long before the object needs it. Eager loading Linq loads and stores all data when the query is run.

For example, if you have a User table and a UserDetails table (the entity associated with the User table) then you would type the code given below. Here, we load the user with an ID equal to the user ID along with the user details.

User usr = dbContext.Users
     .Include (a => a.UserDetails)
     .FirstOrDefault (a => a.UserId == userId);

If we have more than one child level, you can load it using the query below.

User usr = dbContext.Users
     .Include (a => a.UserDetails.Select (ud => ud.Address))
     .FirstOrDefault (a => a.UserId == userId);

This method that returns related entities as part of the query and loads large amounts of data at once saves us time and speed. Using this method is more efficient when we absolutely need the associated data we mentioned in Lazy loading. Because the data is taken from the database in one go, stored in memory and served from the memory when needed. It will save us speed and time since there will be no querying in the database again.

What is explicit Loading ?

In Lazy loading, the required relations are called when requested, while explicit loading is loaded manually with the Load() method.

Is Entity Framework faster than ado net?

Entity framework is slower than ado.net. Because with ado.net, you can operate directly on the database with pure sql queries. However, the entity framework creates a query by considering the data you want to import according to its configurations, table relations, loading selection and these queries usually run slower than your pure sql queries.

One of the main reasons for this slowness is the process of mapping the data retrieved from the database as a result of this query, as well as the complex SQL query created by the entity framework.

What is the difference between ADO net and Entity Framework?

  • While creating a connection with the codes we have written in ADO.NET, we can create Entities in a few clicks in Entity Framework.
  • We can write the code that we will write in lines in ADO.NET, and the code that will call all the data in a single line in Entity Framework.
  • While there is a compatibility problem in ADO.NET, there is no compatibility problem in Entity Framework.
  • If there is an error in the code we wrote in ADO.NET, most of the time it will not tell where our error is. But in the Entity Framework, Maaşallah will know that we will write the code almost without writing it.

What do Pluralize and Singularize terms mean in Entity Framework context?

In database first approaches, it converts the tables in the entity framework database into classes that we will use in our code. Pluralize feature allows the pluralization of the name to be used when creating classes from the tables in the database. In other words, if we have a table named “customer”, the class name we will use in the code will be created as “customers”. This will prevent the table names in the database from colliding with the existing classes in our project.

How Are primary and foreign keys supported in Entity Framework?

Entity framework primary key and foreign key definitions can be made in 2 ways. The first is the data notations and the second is FluentAPI.

When using data notation, we can specify the Primary Key field in the entity class with [Key] notation. The sample code is as follows.

public class Customer
{
    [Key]
    public int CustomerId {get; set;}
    public int FirstName {get; set;}
    public int LastName {get; set;}
}

With this notation, we are telling Entity Framework that we will use the CustomerId field in our Customer table as our PrimaryKey.

With FluentAPI, they can determine the properties of the fields of the table with OnModelCreating method in DbContext.

protected override void OnModelCreating (DbModelBuilder modelBuilder)
{
      modelBuilder.Entity <Customer> ()
      HasKey (t => t.CustomerId);
}

With the HasKey method, we specify which properties of our entity will be used as primary key.

Foreign key definitions can also be made with 2 methods in the same way. If it will be done with data notation, we specify which area you will enable to determine this property on our relation property, which we define as virtual in our entity class. You will use our entity class that specifies customer orders in our scenario. Every order has to have a customer

public class Order
{
    [Key]
    Public int OrderId {get; set;}
    public decimal Amount {get; set;}

    public int CustomerId {get; set;}

    [ForeignKey ("CustomerId")]
    public virtual Customer Customer {get; set;}
}

We have stated that with the definition of [ForeignKey (“CustomerId”)], the relationship between Customer and Order will be provided through the CustomerId property. The FluentAPI method might seem a little easier. Again, we need to override the OnModelCreating method.

 

protected override void OnModelCreating (DbModelBuilder modelBuilder)
modelBuilder.Entity <Order> ()
       .HasRequired (c => c.Customer)
       .WithMany (p => p.Orders)
       .HasForeignKey (c => c.CustomerId);
}

How do you delete an entity?

Section Paragraph There are several ways to delete Entity within the Entity Framework. The first one is to delete directly from the entity and save the changes. The code block below can be used for this example.

context.Remove (context.Customer.Single (a => a.Customer == 1));
context.SaveChanges ();

The second method is to change the entity state. It contains state over entities and when the savechanges method is called, the entity understands which operations it will perform over the framework entities through this state. The following code block can be used for this example.

context.Entry (customer) .State = EntityState.Deleted;
context.SaveChanges ();

What are entity states?

Entity State is briefly a property that informs the current state of our Entity. The situation changes after various operations on the Entity.
You can see the status of our Entity with the State property.

context.Entry (customer) .State

Added
It is the situation that occurs when our Entity is added to the Context. A new record that does not exist has been created on the Entity, that is, an insert has been made.
The insert process has not been reflected in the database yet, it will also be reflected in the database with the SaveChanges operation.
The state state of Entity will change to UnChanged after SaveChanges operation.

Unchanged
It is the situation that no change is made to the Entity taken over the context.

Deleted
The deletion of the relevant Entity over Context has been realized.
Deletion has not been done on the database yet, only on Context.
When the SaveChanges operation is done, the relevant record will be deleted from the database and the Entity State will change to Detached.

Modified
Indicates that the Entity has been modified.
Changes will also be reflected in the database with the SaveChanges operation.
After SaveChanges, the entity state will change to UnChanged.

Detached
Entity is not monitored by a context. So there is no active connection between Entity and Context.

How do you perform entity validation ?

Entity validations can be made at controller level or context. Controls at the controller level can be done manually or using an external tool. Performing manual checks is not useful as it requires writing new code for each new method. Therefore, it makes more sense to use an external tool when validating at the controller level. Fluent Validation is one of the most common. By operating the rules you predefined in your properties, you can prevent the entries of larger or smaller values, depending on the value, length, and limit you set. You can also specify the message that should be displayed when a parameter does not comply with these rules. In this way, users who want to make transactions in your database will understand better what they are missing and find solutions quickly. Below is a sample validation code.

 

public CustomerValidator ()
{
     RuleFor (c => c.FirstName) .NotEmpty (). WithMessage (“FirstName parameter cannot be empty”);
     RuleFor (c => c.LastName) .NotEmpty (). WithMessage (“LastName parameter cannot be empty”);
     RuleFor (c => c.BornDate) .Must (d => d.Year <= 2000) .WithMessage (“Born date should be lower than 2000”);
}

You can use data annotations as a method. These notations are defined on the property in your entity class. Again, when a data that does not comply with the specified rule is sent, they can contain the message that should be shown to the user. The above method works when users send requests while using your methods, data annotations work when their changes are reflected in the database.

class Customer
{
public int Id {get; set; }
[Required (ErrorMessage = "FirstName parameter cannot be empty")]
public string FirstName {get; set; }
[Required (ErrorMessage = "LastName parameter cannot be empty")]
public string LastName {get; set; }
}

What is the difference between Code First, Model First and Database first approach?

All these approaches represent the relationship between database and my entity classes.

With the Code First approach, we first create our entity classes, determine the types and boundaries of our database fields in DbContext and the relationships between the tables. Then, the entity framework creates our database using these configurations. Code first approach provides the opportunity to easily create our database in different environments. Because the necessary tables and configurations for the database are already in our code.

With the model first approach, while any table and entity class has not yet been created, our database model is created using ef designer, and our database and entity classes are created through it.

The database first approach is often used to link code to an already existing database. In other words, first we create our database, then we enable the entity framework to create our entity classes over the created tables.

How do you execute Stored procedures in Entity Framework?

Entity framework allows you to manage your database operations without writing sql queries. However, thanks to its flexible structure, there is a method that you can run pure sql query whenever you need it. Store procedures can also be run over this method. Normally, we can run the sql query as a parameter by giving the name of our store procedure to this method. We do this again with the Database utility on our DbContext class. The following code will run the procedure named “ExampleStoreProcedure”.

ExampleContext context = new ExampleContext ();
context.Database.ExecuteSqlCommand ("ExampleStoreProcedure");

What are transactions ?

Imagine you made changes to the tables on the database. Whether this is an insert, update or delete operation. At this point, if your transaction will affect one or a few different points and you want to undo all the transactions in case you get an error even at one of these points, you should use transactions.

The best example of this is transactions that affect more than one user. For example, you have a system that enables money transfer between users. One user wants to send money to another. In this case, we need to do 2 operations in the simplest form. The first is that the balance in the account of the sending user has decreased by the amount he wants to send, and the second is that the balance in the account of the user to whom he wants to send the money increases by the amount sent. While this process is happening, imagine a problem with your code after reducing the balance of the first user. The balance of the first user decreased, but the balance of the second user did not increase. This is undesirable. In the scenario where transaction is used, you can put back the amount deducted from the balance of the first user by making a rollback.

How do you implement transactions in entity Framework ?

To use transactions, we need the DbContext class. We can start a transaction with the database object over the context. We must do the transaction initiation before all database transactions so that the transaction can cover these changes. This is because if things do not go well, the changes that will be undone should be known. If we can call the SaveChanges method without any problems, we need to use the transaction.Commit () method to reflect the changes in the database. If things do not go well, we can undo the changes made with the transaction.Rollback () method. The general usage of the rollback method is in the Cath block of try catch blocks. When any error occurs, it will be caught in the catch method and we will be able to undo our operations. The code example below sums up what’s been told.

using (var transaction = context.Database.BeginTransaction())
{
     try
     {
         Customer customer = new Customer();
         customer.FirstName = "John";
         customer.LastName = "Doe";
         context.Employees.Add(employee);
         context.SaveChanges();

         BankAccount account = new BankAccount();
         account.Balance = 100;
         account.Type = 1;
         context.Departments.Add(dept);
         context.SaveChanges();
         transaction.Commit();
    }
    catch (Exception ex)
    {
         transaction.Rollback();
    }
}

What are data annotations ?

Data annotations are structures that allow the code side of our fields in the database to be assigned values ​​based on certain rules. Properties are specified by overwriting them. Fields that do not meet the rules contained in these notations will cause the code to throw an error at the time the database changes are saved and will not allow the operation.

  • [Key] : Field is specified as the primary key and is set as an auto-incrementing number when creating the database.
  • [Required] :  Indicates that the field is required.
  • [Column]: The settings related to the field of the field in the database are specified. The domain name (Name), type name (TypeName) or Order (Sequence – Used in Multi Key usage)
  • [DataType] : Sample DataTypes with the data type of the field are as follows. Date, Time, Currency, EmailAdress, Password etc.
  • [HiddenInput] : Ensures that the field is not displayed on the page, but the data is sent to the server, only hidden from the user.
  • [ReadOnly] :  Used to make the field readable only.
  • [DisplayFormat] : The format information to be printed on the page is determined and it is generally used in situations such as Date, Time, Number formatting.
  • [Table] : The name (Name) or Schema (Schema) of the table to be created in the Database is specified.
  • [StringLength] : Used to limit the number of characters to be entered.
Facebook
Twitter
LinkedIn

Our website uses cookies that help it to function, allow us to analyze how you interact with it, and help us to improve its performance. By using our website you agree by our Terms and Conditions and Privacy Policy.