Inno IV- EF Core Flashcards

1
Q

EF Core supports two development approaches

A

1) Code-First
2) Database-First.

EF Core mainly targets the code-first approach and provides little support for the database-first approach because the visual designer or wizard for DB model is not supported as of EF Core.

In the code-first approach, EF Core API creates the database and tables using migration based on the conventions and configuration provided in your domain classes. This approach is useful in Domain Driven Design (DDD).

In the database-first approach, EF Core API creates the domain and context classes based on your existing database using EF Core commands. This has limited support in EF Core as it does not support visual designer or wizard.

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

EF Core vs EF 6

A

Entity Framework Core is the new and improved version of Entity Framework for .NET Core applications. EF Core is new, so still not as mature as EF 6.

EF Core continues to support the following features and concepts, same as EF 6:

  1. DbContext & DbSet
  2. Data Model
  3. Querying using Linq-to-Entities
  4. Change Tracking
  5. SaveChanges
  6. Migrations
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Entities

A

Entities in the Entity Framework are mapped to the corresponding tables in the database. Entity Framework keeps track of these entities so that It can perform database CRUD (Create, Read, Update, Delete) operations automatically based on their objectes status.

Domain classes include the core functionality and business rules of the application, ensuring that the business logic is properly implemented.

The Student and Grade classes are domain classes. To treat them as entities, we need to include them as DbSet<T> properties in the DbContext class of Entity Framework so that EF engine can track their status</T>

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

DbContext in Entity Framework Core

A

The DbContext class is an integral part of the Entity Framework.

An instance of DbContext represents a session with the database which can be used to query and save instances of your entities to a database.

DbContext is a combination of the Unit Of Work and Repository patterns.

DbContext in EF Core allows us to perform the following tasks:

Manage database connection
Configure model & relationship
Querying database
Saving data to the database
Configure change tracking
Caching
Transaction management

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

DbSet

A

We can turn domain classes into entities by specifying them as DbSet<TEntity> type properties.</TEntity>

The DbSet<TEntity> type allows EF Core to query and save instances of the specified entity to the database. LINQ queries against a DbSet<TEntity> will be translated into queries against the database.</TEntity></TEntity>

There are two ways using which you can create a database and schema:

Using the EnsureCreated() method

Using Migration API

Creating a database using the EnsureCreated() method is common to use following by EnsureDeleted() method when testing or prototyping using Entity Framework Core framework.

The DbContext in Entity Framework Core includes the ChangeTracker property of type ChangeTracker class which is responsible of tracking the state of each entity retrieved using the DbContext instance. ⇒ Note that it is not intended to use it directly in your application code. It is just to understand how EF track changes of entities.

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

Migrations

A

Migration is a way to keep the database schema in sync with the EF Core model by preserving data.

EF Core API builds the EF Core model from the entity classes, Data Annotations attributes applied on entity classes and Fluent API configurations in the DbContext class.

EF Core migrations API will create or update the database schema based on the EF Core model. Whenever you change the domain classes, you need to run migration commands to keep the database schema up to date.

EF Core migrations are a set of commands which you can execute in Package Manager Console or PowerShell or in .NET Core CLI (Command Line Interface).

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

The Add-Migration

A

The Add-Migration command does not create the database. It just creates the two snapshot files in the Migrations folder.

<timestamp>_<Migration>.cs: The main migration file which includes migration operations in the Up() and Down() methods. **The Up() method includes the code for creating DB objects and the Down() method includes code for removing DB objects.**

<contextclassname>**ModelSnapshot.cs: A snapshot of your current model**. This is used to determine what changed when creating the next migration.
</contextclassname></Migration></timestamp>

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

dotnet ef database update

A

If you want to revert the database to any of the previous state then you can do it by using the update-database <migration-name> command.</migration-name>

dotnet ef migrations list- List all the migrations
dotnet ef migrations remove- removes the last migrations

It is recommended to deploy migrations to a production database is by generating SQL scripts.

dotnet ef migrations script

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

Saving data and querying

A

There are two scenarios to save an entity data:
1. connected
2. disconnected.

In the connected scenario, the same instance of DbContext is used in retrieving and saving entities, whereas this is different in the disconnected scenario. In this chapter, you will learn about saving data in the connected scenario.

As per the above figure, Entity Framework builds and executes INSERT, UPDATE, or DELETE statements for the entities whose EntityState is Added, Modified, or Deleted when the DbContext.SaveChanges() method is called. In the connected scenario, an instance of DbContext keeps track of all the entities and so it automatically sets an appropriate EntityState of each entity whenever an entity is created, modified, or deleted.

The DbSet class is derived from IQuerayable. So, we can use LINQ for querying against DbSet, which will be converted to an SQL query.

EF API executes this SQL query to the underlying database, gets the flat result set, converts it into appropriate entity objects and returns it as a query result.

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

Eager and lazy loading

A

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query, so that we don’t need to execute a separate query for related entities. Eager loading is achieved using the Include() method.

Lazy loading is delaying the loading of related data, until you specifically request for it. It is the opposite of eager loading. For example, the Student entity contains the StudentAddress entity. In the lazy loading, the context first loads the Student entity data from the database, then it will load the StudentAddress entity when we access the StudentAddress property as shown below.

Even with lazy loading disabled (in EF 6), it is still possible to lazily load related entities, but it must be done with an explicit call. Use the Load() method to load related entities explicitly. Consider the following example.

EF Core will create database tables for all DbSet<TEntity> properties in a context class with the same name as the property. It will also create tables for entities which are not included as DbSet properties but are reachable through reference properties in other DbSet entities.</TEntity>

EF Core creates a clustered index on Primarykey columns and a non-clustered index on ForeignKey columns, by default.

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

Configurations in Entity Framework Core-2 ways

A

By using Data Annotation Attributes
By using Fluent API

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

Data Annotations

A

Data Annotations is a simple attribute based configuration method where different .NET attributes can be applied to domain classes and properties to configure the model.

Data annotation attributes are not dedicated to Entity Framework, as they are also used in ASP.NET MVC. This is why these attributes are included in separate namespace System.ComponentModel.DataAnnotations.

[Column(“Name”, TypeName=”ntext”)]
[MaxLength(20]
[Key]

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

Fluent API

A

Another way to configure domain classes is by using Entity Framework Fluent API. EF Fluent API is based on a Fluent API design pattern (a.k.a Fluent Interface) where the result is formulated by method chaining.

In Entity Framework Core, the ModelBuilder class acts as a Fluent API. By using it, we can configure many different things, as it provides more configuration options than data annotation attributes.

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

Model Configuration

A

Model Configuration: Configures an EF model to database mappings. Configures the default Schema, DB functions, additional data annotation attributes and entities to be excluded from mapping.

Entity Configuration: Configures entity to table and relationships mapping e.g. PrimaryKey, AlternateKey, Index, table name, one-to-one, one-to-many, many-to-many relationships etc.

Property Configuration: Configures property to column mapping e.g. column name, default value, nullability, Foreignkey, data type, concurrency column etc.

modelBuilder.Entity<Student>()
.Property(s => s.StudentId)
.HasColumnName("Id")
.HasDefaultValue(0)
.IsRequired();</Student>

Fluent API configurations have higher precedence than data annotation attributes.

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

Fluent API and Data Anotations precedence

A

Fluent API configurations have higher precedence than data annotation attributes.

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

Shadow properties

A

Shadow properties are the properties that are not defined in your .NET entity class directly; instead, you configure it for the particular entity type in the entity data model. They can be configured in the OnModelCreating() method of the context class.

protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<Student>().Property<DateTime>("CreatedDate");
modelBuilder.Entity<Student>().Property<DateTime>("UpdatedDate");
}</DateTime></Student></DateTime></Student>

Entity Framework Core provides the DbSet.FromSql() method to execute raw SQL queries for the underlying database and get the results as entity objects.

17
Q

Stored procedures

A

EF Core provides the following methods to execute a stored procedure:

DbSet<TEntity>.FromSql()
DbContext.Database.ExecuteSqlCommand()</TEntity>

18
Q

What are the different states an entity can have in EF Core?

A

Detached, Unchanged, Added, Modified, Deleted.

19
Q

Explain the difference between a tracked and an untracked entity in EF Core.

A

A tracked entity is being tracked by the DbContext for changes (i.e., EF Core keeps track of the entity’s state and will persist any changes to the database), while an untracked entity is not being tracked by EF Core and will not persist changes unless explicitly attached.

20
Q

How can you change the state of an entity in EF Core?

A

You can change the state of an entity using methods like DbContext.Entry(entity).State, setting it to EntityState.Added, EntityState.Modified, EntityState.Deleted, or EntityState.Detached.

21
Q

What happens when an entity is in the Detached state?

A

When an entity is detached, it is no longer tracked by the DbContext. Changes made to this entity will not be persisted to the database unless it is re-attached to a DbContext.

22
Q

What is the Unchanged entity state in EF Core?

A

The Unchanged state means that an entity has been loaded from the database and has not been modified since. No changes are tracked, so no updates will be sent to the database when SaveChanges is called.

23
Q

What is the role of DbContext.Entry(entity) in EF Core?

A

DbContext.Entry(entity) provides access to the metadata and state information of the given entity, allowing you to get or set the state of the entity (e.g., EntityState.Added, EntityState.Modified).

24
Q

Eager Loading

A

Definition: Eager loading is the process of loading related entities as part of the initial query. When you query the main entity, EF Core automatically loads related entities using the Include() method.

Usage: Use eager loading when you want to retrieve related entities along with the main entity in a single query.

When to Use: When you know you will need related entities right away and want to avoid additional queries.

25
Lazy Loading
Definition: Lazy loading is a mechanism **where related entities are automatically loaded only when they are accessed for the first time**. The related data is not loaded when the main entity is retrieved, but when you access the navigation property of that entity. Usage: Lazy loading is enabled by creating virtual navigation properties, and EF Core uses proxies to load related data on demand. To enable lazy loading, EF Core requires enabling it through configuration or via proxy creation. This can be done by installing the Microsoft.EntityFrameworkCore.Proxies package and enabling it in DbContext: options.UseLazyLoadingProxies();
26
Explicit Loading
Definition: Explicit loading is **when you manually load related entities after the initial query has been executed**. You first load the main entity and then explicitly load related entities using methods like **Load().** Usage: Use explicit loading when you want to load related entities conditionally or at a later time after the main entity has been loaded. When to Use: When you want full control over when and how related data is loaded, or when you need to load additional related data based on certain conditions.