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

Date/time operations are not supported


Most direct operations with DateTime objects are not supported.

Problem

It is often necessary to produce operations over DateTime properties, such as, for example, computing the difference between two columns. In the past (Entity Framework pre-Core), there was a class called DbFunctions (https://msdn.microsoft.com/en-us/library/system.data.entity.dbfunctions(v=vs.113).aspx) that had some useful extension methods that we could use for this.

Unfortunately, as of Entity Framework Core 1, this class is not included. This means that the following queries do not work or will not work as expected–in this example, AddDays will be executed client-side, not in the database:

var age = ctx
  .Blogs
  .Select(b => DateTime.UtcNow – b.CreationDate)
  .ToList();
var oneWeekAfterCreation = ctx
  .Blogs
  .Select(b => b.CreationDate.AddDays(7))
  .ToList();

How to solve it…

For queries that need to perform complex date/time operations in the database side, we need to resort to plain SQL; there is no way around it. For example, the first of these queries could be rewritten as follows:

var age = ctx
  .Blogs
  .FromSql("SELECT GETUTCDATE() – CreationDate AS CreationDate FROM Blogs")
  .Select(b => b.CreationDate)
  .ToList();

And the second could be rewritten as follows:

var oneWeekAfterCreation = ctx
  .Blogs
  .FromSql("SELECT DATEADD(day, 7, CreationDate) AS CreationDate FROM Blogs")
  .Select(b => b.CreationDate)
  .ToList();