Book Image

Entity Framework Core Cookbook - Second Edition

By : Ricardo Peres
Book Image

Entity Framework Core Cookbook - Second Edition

By: Ricardo Peres

Overview of this book

Entity Framework is a highly recommended Object Relation Mapping tool used to build complex systems. In order to survive in this growing market, the knowledge of a framework that helps provide easy access to databases, that is, Entity Framework has become a necessity. This book will provide .NET developers with this knowledge and guide them through working efficiently with data using Entity Framework Core. You will start off by learning how to efficiently use Entity Framework in practical situations. You will gain a deep understanding of mapping properties and find out how to handle validation in Entity Framework. The book will then explain how to work with transactions and stored procedures along with improving Entity Framework using query libraries. Moving on, you will learn to improve complex query scenarios and implement transaction and concurrency control. You will then be taught to improve and develop Entity Framework in complex business scenarios. With the concluding chapter on performance and scalability, this book will get you ready to use Entity Framework proficiently.
Table of Contents (15 chapters)
Entity Framework Core Cookbook - Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Refreshing entities


Because of the first level cache, reloading an entity with modified database values will not refresh it.

Problem

Entity Framework Core, like other Object-Relational Mappers, uses something called a First Level Cache (also known as Identity Map) to keep track of the entities that it knows about. These are entities that were loaded from the database or ones that have been marked for persistence. This, in general, can be regarded as an optimization: when Entity Framework loads the same record over and over again, it does not need to instantiate the entity's class and hydrate it with the values coming from the database.

The problem is, what if the entity's record changes in the database and we wish to refresh the ones we have? For example, this won't work:

//retrieve an entity from the database
var myEntity = ctx.MyEntities.First();
//the entity's record changes in the database
//retrieve the entity again
//unchanged: is returned from the first level cache
myEntity = ctx.MyEntities.First();

How to solve it…

The way to solve this is to first detach it from the context, which effectively means removing it from the first level cache, like this:

//retrieve an entity from the database
var myEntity = ctx.MyEntities.First();
//the entity's record changes in the database
//detach the entity
ctx.Entry(myEntity).State = EntityState.Detached;
//retrieve the entity again
myEntity = ctx.MyEntities.First();

This way, you are sure to get the most up-to-date values.