Search icon
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Entity Framework Core Cookbook - Second Edition

You're reading from  Entity Framework Core Cookbook - Second Edition

Product type Book
Published in Nov 2016
Publisher Packt
ISBN-13 9781785883309
Pages 324 pages
Edition 2nd Edition
Languages
Author (1):
Ricardo Peres Ricardo Peres
Profile icon Ricardo Peres

Table of Contents (15) Chapters

Entity Framework Core Cookbook - Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
1. Improving Entity Framework in the Real World 2. Mapping Entities 3. Validation and Changes 4. Transactions and Concurrency Control 5. Querying 6. Advanced Scenarios 7. Performance and Scalability Pitfalls 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();
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}