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

Accessing the service provider too soon


Do not access the internal service provider in OnConfiguring or OnModelCreating.

Problem

The Entity Framework Core context uses a service provider of its own, but it is possible to pass it an external service provider. Having a service provider to hand is appealing, because we can use it to pass any kind of services to the context.

The problem is that most likely, we will be making use of these services in one of the methods that are used to configure the DbContext, such as OnConfiguring or OnModelCreating, but, it turns out, if you try to access the underlying service provider, either the built-in or the passed instance, you will get an "An attempt was made to use the context while it is being configured" exception.

How to solve it…

You should pass all services that you will need in the constructor of the DbContext-derived class and store them internally. Then you can use them in any of the infrastructure methods, such as OnConfiguring or OnModelCreating. If you are using Dependency Injection, like you would in a web application, you can even declare these services as their base classes or interfaces and .NET Core will resolve them for you.

You will be able to access the internal service provider after a query is executed or when the SaveChanges method is called.