0% found this document useful (0 votes)
8 views

tracking-and-saving-data-with-ef-core-slides

Uploaded by

ahmed11611612
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

tracking-and-saving-data-with-ef-core-slides

Uploaded by

ahmed11611612
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Tracking and Saving Data

with EF Core

Julie Lerman
EF Core Expert and Software Coach

@julielerman | thedatafarm.com
Module DbContext and entity roles in tracking
Overview Tracking and saving workflow
Inserting, updating, and deleting objects
Tracking and saving multiple objects
Bulk operation support
How persistence differs in
disconnected apps
Gaining a Better Understanding of
DbContext and Entity
A fundamental
understanding of how
things work will pay off in
productivity.
Tracking Components

DbContext DbContext.ChangeTracker EntityEntry

Represents a session Manages a collection of State info for each


with the database EntityEntry objects entity: CurrentValues,
OriginalValues, State
enum, Entity & more
Entity and the DbContext

In-Memory Objects Entities DbContext


In-memory objects with Contains EntityEntry
key (identity) properties objects with reference
that the DbContext is pointers to in-memory
aware of objects
Understanding Tracking and Saving
Workflow
Tracking and Saving Workflow

EF Core creates
DbContext maintains
tracking object for On SaveChanges
EntityEntries
each entity

Tracking States {Julia Lerman,Modified} • DbContext updates State


• Unchanged (Default) {Josie Newf, Added} for tracked entities
• Added {“How to Newf”, Added}
• Modified • Works with provider to
• Deleted compose SQL statements

• Executes statements
on database

Updates entity PKs Returns #


Resets state info
and FKS Affected & new PKs
Inserting Simple Objects
Add from DbSet or DbContext

context.Authors.Add(…) context.Add(…)

Track via DbSet Track via DbContext


DbSet knows the type DbContext will discover type
DbContext knows that it’s Added Knows it’s Added
Updating Simple Objects
How DbContext Discovers About Changes

DbContext.ChangeTracker.DetectChanges()
Reads each object being tracked and updates state details in
EntityEntry object

DbContext.SaveChanges()
Always calls DetectChanges for you

You can call DetectChanges() in your code if needed


The entities are just plain
objects and don’t
communicate their changes
to the DbContext.
Various Paths for Tracking to Detect Edits

If DbContext is
DbSet and
aware of object, it More advanced:
DbContext also
will detect modify state
have an Update()
changes on directly
method
SaveChanges
Updating Untracked Objects
Begin Tracking and Set State to Modified

context.Authors.Update(…) context.Update(…)

Track via DbSet Track via DbContext


DbSet knows the type DbContext will discover the type
Knows right away that it’s Modified Knows right away that it’s Modified
More Pointers for Disconnected Data

Your app logic will


Update is not Update and Add
need to know
typically needed and Remove are
when to call
when object is important for
Update, Add or
tracked untracked objects
Remove
Deleting Simple Objects
Deleting May Seem a Little Weird

EF Core sends relevant


Context needs to Then you Delete
SQL to database on
track the entity (“Remove”) the entity
SaveChanges
There is no
Delete(id)
similar to Find(id)
Deleting without Querying

Bulk
Delete

Fake object with key Stored procedure Soft delete via ExecuteDelete()
property filled via raw SQL Global Query Filters for untracked data
Watch out for for untracked data Link in resources
possible side Further on in course
effects
Tracking Multiple Objects and Batch
Support
Inserting Multiple Objects

The Tedious Way


context.Authors.Add( new Author { FirstName = "Ruth", LastName = "Ozeki" });
context.Authors.Add( new Author { FirstName = "Sofia", LastName = "Segovia" });
context.Authors.Add( new Author { FirstName = "Ursula K.", LastName = "LeGuin" });
context.Authors.Add( new Author { FirstName = "Hugh", LastName = "Howey" });
context.Authors.Add( new Author { FirstName = "Isabelle", LastName = "Allende" });

Or Build a List<Author> and...


context.Authors.AddRange(authorList);
Tracking Multiple Entities

context.Authors.AddRange(…) context.AddRange(…)

context.Authors.UpdateRange(…) context.UpdateRange(…)

context.Authors.RemoveRange(…) context.RemoveRange(…)

Track via DbSet Track via DbContext


DbSet indicates type Context will discover type(s)
Batched Add/Update/Delete

SQL Server minimum is 2,


Min and Max driven by provider
and maximum is 42

Update & Delete return 1 in


Inserts return new key in OUTPUT
OUTPUT
Batching can combine
types and operations
public class SqlServerModificationCommandBatch :
AffectedCountModificationCommandBatch
{
// https://docs.microsoft.com/sql/sql-server/maximum-capacity-specifications-for-sql-server
private const int DefaultNetworkPacketSizeBytes = 4096;
private const int MaxScriptLength = 65536 * DefaultNetworkPacketSizeBytes / 2;

/// <summary>
/// The SQL Server limit on parameters, including two extra parameters to
/// sp_executesql (@stmt and @params).
/// </summary>
private const int MaxParameterCount = 2100 - 2;

Additional Batch Constraints of SQL Server Provider


Note that min, max, etc. are configurable
Updating and Deleting Multiple
Untracked Objects
The Methods

[Query].ExecuteDelete() [Query].ExecuteUpdate()
Deleting without Querying

Bulk
Delete

Fake object with key Stored procedure Soft delete via ExecuteDelete()
property filled via raw SQL Global Query Filters for untracked data
Watch out for for untracked data Link in resources
possible side Further on in course
effects
Executing Directly in the Database on Untracked Data

Delete (or update) a row when you only know its’ ID

Delete (or update) rows matching a certain criteria

Avoid wasting time and resources retrieving unneeded objects


Execute Means “Do It Now”

Does not interact Returns # of rows


Executes right away
with ChangeTracker affected
ExecuteUpdate

Set a simple value


[Query].ExecuteUpdate(
setters => setters.SetProperty(b => b.PropertyToChange, newvalue)
);

Set a value based on a property


[Query].ExecuteUpdate(
setters => setters.SetProperty(b => b.PropertyToChange,b=>Transform(b.Property))
);
Do not mix tracking and
these Execute methods!
ChangeTracker and SaveChanges provides
a lot of benefits
Review An entity is unaware of the change tracker
Database provider works with EF Core to
send correct and efficient commands
Batches insert, update, and delete
commands to reduce roundtrips
Determines if an explicit transaction is
needed or not
DB generated values returned efficiently
and propagated back into entities
Up Next:

Controlling Database Creation and


Schema Changes with Migrations
Resources

Entity Framework Core on GitHub: github.com/dotnet/efcore

EF Core Documentation: learn.microsoft.com/ef/core

Article about SQL Server Merge Joins:


brentozar.com/archive/2017/05/case-entity-framework-cores-odd-sql/

Soft Delete with Global Query Filters in EF Core Docs:


learn.microsoft.com/ef/core/querying/filters

You might also like