Entity Flashcards

1
Q

What is Entity Framework?

A

In .NET applications (desktop and web), ADO.NET is an old and powerful method for accessing databases and requires a lot of coding. Simply put, all of the work is done manually. Microsoft has therefore introduced Entity Framework to automate the database technique.

Entity Framework (EF), a Microsoft-supported open-source ORM (Object-Relational Mapper) for .NET applications, is a set of utilities and mechanisms that works towards optimizing data-driven applications. This is considered one of the most important concepts in the MVC model. With the help of tables and columns, developers are able to streamline mapping between various objects in software applications. It makes use of objects of domain-specific classes but ignores the database tables and columns that are used to store the data. Designers can utilize EF in order to maintain and develop data-oriented applications with little coding and a high level of absorption when dealing with data, unlike traditional applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Explain what the .edmx file contains.

A

First of all, a database lets you reverse engineer a model from an existing database. Entity Framework Designer is used to view and edit models stored and created in EDMX files (.edmx extensions). Using the EDMX file, you automatically generate classes that you can interact with within your application.

EDMX files represent conceptual models, storage models, and their mappings. This file contains all the mapping information between SQL tables and objects. In addition, it also includes essential information required for rendering models graphically with ADO.NET Entity Data Designer. Furthermore, it is divided into three divisions, CSDL, MSL, and SSDL.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What do you mean by migration? Write its type.

A

Migration is a tool that was introduced in EF to update the database schema automatically when a model is modified without losing any data or other objects. Migrate Database To Latest Version is a new database initializer used by it. Entity Framework offers two types of migration:

Automated Migration: Entity Framework 4.3 was the first to introduce automated migration so you don’t have to manually migrate databases every time you alter a domain class. For example, you must also change the domain classes for each time you make a change, but with automated migration, you can simply run a command through the Package Manager Console.
Code-based Migration: When you use a code-based migration, you can configure additional aspects of the migration, like setting the default value of a column, configuring a computed column, etc

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are different types of Entity framework approaches?

A

Code First Approach: The Code First approach primarily uses classes to create the model and its relations, which are then used to create a database. This way, developers can work in an object-oriented manner without considering the database structure. By following this model, developers first write POCO classes and then use these classes to create the database. Code First is the method used by most developers using Domain-Driven Design (DDD).

Model First Approach: In contrast, the Model First approach uses ORM to build model classes and their relationships. Following the successful creation of the model classes and relationships, the physical database is created using these models.

Database-First Approach: In Entity Framework, Database First approach is used to build entity models based on existing databases and reduce the amount of code required. By using this approach, domain and context classes can be created based on existing classes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are different entity states in EF?

A

Added: It is a state in which an entity exists within the context but does not exist within the database. When the user invokes the SaveChanges method, DbContext usually generates an INSERT SQL query to insert the data into the database. Upon successful completion of the SaveChanges method, the entity’s state changes to unchanged.

Deleted: This state indicates that the entity is marked for deletion has not been removed from the database. Also, it indicates the existence of the entity in the database. When the user invokes the SaveChanges method, DbContext usually generates a DELETE SQL query to delete or remove the entity from the database. Upon successful completion of the delete operation, DbContext removes the entity.

Modified: When the entity is modified, its state becomes Modified. Also, it indicates the existence of the entity in the database. When the user invokes the SaveChanges method, DbContext usually generates an UPDATE SQL query to update the entity from the database. Upon successful completion of the SaveChanges method, the entity’s state changes to unchanged.

Unchanged: Since the context retrieved the entity’s property values from the database, the values have not changed. This entity is ignored by SaveChanges.

Detached: This state indicates that the entity is not tracked by the DbContext. If an entity was created or retrieved outside the domain of the current instance of DbContext, then its entity state will be Detached.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Explain the term dbcontext and dbset.

A

DbSet: An entity set is represented by a DbSet class that can be used for creating, reading, updating, and deleting operations on it. Those DbSet type properties, which map to database tables and views, must be included in the context class (derived from DbContext).

DbContext: It is considered an essential class in EF API that bridges the gap between an entity or domain class and the database. Communication with the database is its primary responsibility

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Explain POCO Classes in EF.

A

POCO stands for ‘Plain Old CLR Objects’. Yet, it does not mean these classes are plain or old. A POCO class is defined as a class that contains no reference to the EF Framework or the .NET Framework at all. In EF applications, Poco entities are known as available domain objects.

POCO class is just like other normal .NET classes as these classes don’t depend on any framework-specific base class, unlike the standard .NET class. Persistence-ignorant objects, or POCOs, support LINQ queries, which are supported by entities derived from the Entity Object itself. Both EF 6 and EF Core support POCO entities

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are different types of loading available to load related entities in EF?

A

Lazy Loading: This process delays the loading of related objects until they are needed. During lazy loading, only the objects needed by the user are returned, whereas all other related objects are only returned when needed.

Eager Loading: This process occurs when you query for an object and all of its related objects are returned as well. Aside from that, all related objects will load with the parent object automatically. When the Include method is used, eager loading can be achieved in EF6.

Explicit Loading: Explicit loading occurs only when lazy loading is desired, even when lazy loading is disabled. We must explicitly call the relevant load method on the related entities to process explicit loading. When the Load method is used, explicit loading can be achieved in EF6

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is Entity Framework (EF)?

A

Entity Framework is an ORM (Object-Relational Mapping) framework provided by Microsoft. It enables developers to work with databases using .NET objects and eliminates the need for most of the data-access code that developers usually need to write.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Explain the different approaches to working with Entity Framework.

A

Entity Framework supports three different approaches:

Database-First: Creates entity classes based on an existing database schema.

Model-First: Allows creating entity classes and relationships visually in the EDMX designer.

Code-First: Enables developers to define entities, relationships, and configurations using code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the key components of Entity Framework Core?

A

DbContext: Represents a session with the database and a gateway to perform CRUD operations.

DbSet: Represents a collection of entities of a particular type within the context.

Entity: Represents a class that corresponds to a table in the database.

LINQ to Entities: Allows querying entities using LINQ.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Explain Lazy Loading and Eager Loading in Entity Framework.

A

Lazy Loading: Lazy loading is the technique where related entities are loaded from the database only when they’re accessed for the first time. It’s the default behavior in Entity Framework Core, and it helps in avoiding unnecessary database calls.

Eager Loading: Eager loading is the technique where related entities are loaded along with the main entity using the Include method or using projection. It reduces the number of database round trips but might fetch unnecessary data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the difference between Add, Attach, and Update methods in Entity Framework Core?

A

Add: Used to add a new entity to the context. It changes the state of the entity to Added.

Attach: Used to re-attach an existing entity to the context. It changes the state of the entity to Unchanged.

Update: Used to update an existing entity in the context. It changes the state of the entity to Modified.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the purpose of migrations in Entity Framework Core?

A

Migrations in Entity Framework Core allow developers to evolve the database schema over time in a structured way. They enable creating, updating, and reverting database schema changes, keeping the database schema in sync with the application’s data model.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How does Entity Framework handle relationships between entities (one-to-one, one-to-many, many-to-many)?

A

Entity Framework supports various types of relationships:
One-to-One: One entity instance is related to exactly one instance of another entity.
One-to-Many: One entity instance is related to multiple instances of another entity.
Many-to-Many: Multiple instances of one entity are related to multiple instances of another entity using a joining table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Explain the advantages and disadvantages of using Entity Framework.

A

Advantages: Rapid development, reduced amount of boilerplate code, easy to maintain, supports various database providers, LINQ support for querying data.

Disadvantages: Performance overhead, potential for generating inefficient queries, complexity in some advanced scenarios, learning curve.

17
Q

What is the purpose of the DbContext class in Entity Framework?

A

The DbContext class in Entity Framework represents the session with the database and provides a set of APIs to perform CRUD (Create, Read, Update, Delete) operations on entities. It also manages the entity objects during their lifecycle.

18
Q

Explain how Entity Framework handles transactions.

A

Entity Framework Core supports transactions through the SaveChanges method. Multiple changes within a single SaveChanges call are made within a transaction. Additionally, you can explicitly manage transactions using Database.BeginTransaction and Transaction.Commit/Transaction.Rollback methods.

19
Q

Przykład operacji na danych zapisanie osoby

A

using (var context = new ApplicationDbContext(options))
{
var person = new Person
{
Name = “John Doe”,
Age = 30,
Addresses = new List<Address>
{
new Address { Street = “123 Main St”, City = “Somewhere”, PostalCode = “12345” },
new Address { Street = “456 Elm St”, City = “Anywhere”, PostalCode = “67890” }
}
};

context.People.Add(person);
context.SaveChanges(); }
20
Q

Pobieranie danych

A

using (var context = new ApplicationDbContext(options))
{
// Pobieranie osoby z jej adresami
var personWithAddresses = context.People
.Include(p => p.Addresses)
.FirstOrDefault(p => p.Id == 1);

Console.WriteLine($"Name: {personWithAddresses.Name}");
foreach (var address in personWithAddresses.Addresses)
{
    Console.WriteLine($"Address: {address.Street}, {address.City}, {address.PostalCode}");
} }
21
Q

Aktualizowanie danych

A

using (var context = new ApplicationDbContext(options))
{
var person = context.People.FirstOrDefault(p => p.Id == 1);
if (person != null)
{
person.Name = “John Smith”;
context.SaveChanges();
}
}

22
Q

Optymalizacja zapytań (Lazy Loading vs Eager Loading)

A

Lazy Loading: Ładowanie powiązanych danych w momencie, gdy są one po raz pierwszy użyte. Entity Framework domyślnie używa lazy loading, ale możesz wymusić Eager Loading, używając metody Include (jak pokazano w poprzednim przykładzie).

Eager Loading: Ładowanie powiązanych danych od razu, w ramach tego samego zapytania do bazy danych. Jest to bardziej wydajne, ponieważ unika dodatkowych zapytań do bazy danych.

23
Q

Usuwanie danych

A

using (var context = new ApplicationDbContext(options))
{
var person = context.People.FirstOrDefault(p => p.Id == 1);
if (person != null)
{
context.People.Remove(person);
context.SaveChanges();
}
}