Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Entity Framework Core Cookbook
Entity Framework Core Cookbook

Entity Framework Core Cookbook: Transactions, stored procedures, query libraries, and more , Second Edition

eBook
$9.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Entity Framework Core Cookbook

Chapter 2. Mapping Entities

In this chapter, we will cover the following topics:

  • Mapping non-public members
  • Mapping interfaces
  • Shadow properties
  • Creating one-to-one maps
  • Creating one-to-many maps
  • Creating many-to-many maps
  • Creating custom conventions
  • Using sequence key generators
  • Using GUIDs as keys
  • Implementing inheritance–Table per class Hierarchy

Introduction

Object-relational mappers such as Entity Framework rely on mappings to translate Object-oriented concepts—classes, properties, references, inheritance – to the database world – composed of tables and columns – and vice versa. For example, a table normally translates to a .NET class, and its columns translate to the class properties.

Mapping entities and their properties is something that Entity Framework does automatically, and does generally well. There are some cases, however, in which we need to give it a hand. In this chapter, we will have a look at some special cases: it's going to be all about mappings.

Mapping non-public members

A well-encapsulated domain model does not contain just public members. The problem is that Entity Framework automatically maps public properties, but does not do so for non-public ones. In this recipe, we will see how we can map non-public properties of entities, so that Entity Framework recognizes them.

Getting ready

We will be using the NuGet Package Manager to install the Entity Framework Core 1 package, Microsoft.EntityFrameworkCore. We will also be using a SQL Server database to store the data, so we will also need Microsoft.EntityFrameworkCore.SqlServer.

Finally, xunit is the package we will be using for the unit tests, and dotnet-text-xunit adds tooling support for Visual Studio. Note that the UnitTests project is a .NET Core App 1.0 (netcoreapp1.0), that Microsoft.EntityFrameworkCore.Design is configured as a build dependency, and Microsoft.EntityFrameworkCore.Tools is set as a tool.

Open Using EF Core Solution from the included source code examples.

Execute...

Mapping interfaces

Other than mapping whole classes, it is also possible to define attributes of properties that are, for example, defined in interfaces. This kind of mapping could apply to several classes, all those that implement the given interface.

Getting ready

We will be using the NuGet Package Manager to install the Entity Framework Core 1 package, Microsoft.EntityFrameworkCore. We will also be using a SQL Server database to store the data, so we will also need Microsoft.EntityFrameworkCore.SqlServer.

Finally, xunit is the package we will be using for the unit tests, and dotnet-text-xunit adds tooling support for Visual Studio. Note that the UnitTests project is a .NET Core App 1.0 (netcoreapp1.0), that Microsoft.EntityFrameworkCore.Design is configured as a build dependency, and Microsoft.EntityFrameworkCore.Tools is set as a tool.

Open Using EF Core Solution from the included source code examples.

Execute the database setup script from the code samples included for this recipe. This...

Shadow properties

Going one step further from private properties, in a well-defined model, it may make sense to hide certain properties from the developers so that they do not make unwanted changes to them, consciously or not.

Historically, Entity Framework, like most ORMs, has three models:

  • POCO model: This represents the .NET classes and their properties and references
  • Database model: This represents the tables, views, and columns (in the case of relational data stores) where data is actually stored
  • Mapping model: This model binds the two preceding models; this is where we say that the MyEntity class is to be stored in the MY_ENTITY table and the Id property goes into the MY_ENTITY_ID column

Note

Entity Framework used to call these models Conceptual Model, Storage Model, and Mapping Model. If you are curious, refer to the following link:

https://msdn.microsoft.com/en-us/data/jj650889.

So, what we are looking for is a way to have a backing data store for entities and properties that does not...

Creating one-to-one maps

Entities can be related to each other in different ways. A one-to-one relation is one where each individual entity may be related to another, and this other one, if it exists, is directly related to the first. Examples include the following:

  • A relation from a person to their address, assuming that no two people share the same address
  • Additional details for an order
  • A person and their pet
  • A country and its head of state

A one-to-one relation is easy to represent in domain model terms: each of the entities has a reference to the other. Only one side can be made required; otherwise, we would have a problem: which one comes first? Let's see how we can map this kind of relation in Entity Framework Core.

Getting ready

We will be using the NuGet Package Manager to install the Entity Framework Core 1 package, Microsoft.EntityFrameworkCore. We will also be using a SQL Server database to store the data, so we will also need Microsoft.EntityFrameworkCore.SqlServer.

Finally, xunit...

Creating one-to-many maps

When an entity can be associated with one or more entities of another type, and each of these entities is associated with at most one entity of the first type, we call that one-to-many. It is one of the more basic kinds of relation, and, if looked at from the other endpoint, it becomes a many-to-one relation. Some examples of this include the following:

  • A blog and its posts
  • A parent and their children
  • A folder and its sub-folders
  • An order and its details (items included)

You may notice that there is one difference: in some of these relations, the many side cannot exist without the one—for example, a child without a parent–while in others, it can—there can be a folder without a parent folder.

This is easy to represent in the domain model; the one side holds a collection of entities of the many side, and the many side holds a reference to an entity on the one side. Pretty simple.

Getting ready

We will be using the NuGet Package Manager to install the...

Creating many-to-many maps

A many-to-many relation is another of those "canonical" ones. Essentially, each entity on one of the sides can be associated with many entities on the other side, and this goes the other way too. Just think of these use cases:

  • A post and its tags, where a tag can have multiple posts and a post multiple tags
  • Books and authors
  • Projects and developers

Usually, a many-to-many relation is easy to represent in classes: each side holds a collection of entities of the other side. In Entity Framework Core, however, things are not so simple. I'm sorry to break this to you, but as it happens, many-to-many relations are not supported! Do not be alarmed, though, there's still something we can do about it! This was a change from previous versions (Entity Framework 6.x) and one that will certainly be fixed. In the meantime, let's get it working.

Note

In Entity Framework Core, many-to-many relations are simulated with a middle entity. This even allows you to...

Introduction


Object-relational mappers such as Entity Framework rely on mappings to translate Object-oriented concepts—classes, properties, references, inheritance – to the database world – composed of tables and columns – and vice versa. For example, a table normally translates to a .NET class, and its columns translate to the class properties.

Mapping entities and their properties is something that Entity Framework does automatically, and does generally well. There are some cases, however, in which we need to give it a hand. In this chapter, we will have a look at some special cases: it's going to be all about mappings.

Mapping non-public members


A well-encapsulated domain model does not contain just public members. The problem is that Entity Framework automatically maps public properties, but does not do so for non-public ones. In this recipe, we will see how we can map non-public properties of entities, so that Entity Framework recognizes them.

Getting ready

We will be using the NuGet Package Manager to install the Entity Framework Core 1 package, Microsoft.EntityFrameworkCore. We will also be using a SQL Server database to store the data, so we will also need Microsoft.EntityFrameworkCore.SqlServer.

Finally, xunit is the package we will be using for the unit tests, and dotnet-text-xunit adds tooling support for Visual Studio. Note that the UnitTests project is a .NET Core App 1.0 (netcoreapp1.0), that Microsoft.EntityFrameworkCore.Design is configured as a build dependency, and Microsoft.EntityFrameworkCore.Tools is set as a tool.

Open Using EF Core Solution from the included source code examples.

Execute...

Mapping interfaces


Other than mapping whole classes, it is also possible to define attributes of properties that are, for example, defined in interfaces. This kind of mapping could apply to several classes, all those that implement the given interface.

Getting ready

We will be using the NuGet Package Manager to install the Entity Framework Core 1 package, Microsoft.EntityFrameworkCore. We will also be using a SQL Server database to store the data, so we will also need Microsoft.EntityFrameworkCore.SqlServer.

Finally, xunit is the package we will be using for the unit tests, and dotnet-text-xunit adds tooling support for Visual Studio. Note that the UnitTests project is a .NET Core App 1.0 (netcoreapp1.0), that Microsoft.EntityFrameworkCore.Design is configured as a build dependency, and Microsoft.EntityFrameworkCore.Tools is set as a tool.

Open Using EF Core Solution from the included source code examples.

Execute the database setup script from the code samples included for this recipe. This...

Shadow properties


Going one step further from private properties, in a well-defined model, it may make sense to hide certain properties from the developers so that they do not make unwanted changes to them, consciously or not.

Historically, Entity Framework, like most ORMs, has three models:

  • POCO model: This represents the .NET classes and their properties and references

  • Database model: This represents the tables, views, and columns (in the case of relational data stores) where data is actually stored

  • Mapping model: This model binds the two preceding models; this is where we say that the MyEntity class is to be stored in the MY_ENTITY table and the Id property goes into the MY_ENTITY_ID column

Note

Entity Framework used to call these models Conceptual Model, Storage Model, and Mapping Model. If you are curious, refer to the following link:

https://msdn.microsoft.com/en-us/data/jj650889.

So, what we are looking for is a way to have a backing data store for entities and properties that does not...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn how to use the new features of Entity Framework Core 1
  • Improve your queries by leveraging some of the advanced features
  • Avoid common pitfalls
  • Make the best of your .NET APIs by integrating with Entity Framework

Description

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.

Who is this book for?

This book is for .NET developers who work with relational databases on a daily basis and understand the basics of Entity Framework, but now want to use it in a more efficient manner. You are expected to have some prior knowledge of Entity Framework.

What you will learn

  • Master the technique of using sequence key generators
  • Validate groups of entities that are to be saved / updated
  • Improve MVC applications that cover applications developed using ASP.NET MVC Core 1
  • Retrieve database information (table, column names, and so on) for entities
  • Discover optimistic concurrency control and pessimistic concurrency control.
  • Implement Multilatency on the data side of things.
  • Enhance the performance and/or scalability of Entity Framework Core
  • Explore and overcome the pitfalls of Entity Framework Core

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 09, 2016
Length: 324 pages
Edition : 2nd
Language : English
ISBN-13 : 9781785880582
Vendor :
Microsoft
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 09, 2016
Length: 324 pages
Edition : 2nd
Language : English
ISBN-13 : 9781785880582
Vendor :
Microsoft
Category :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 152.97
Learning ASP.NET Core MVC Programming
$48.99
Mastering C# and .NET Framework
$48.99
Entity Framework Core Cookbook
$54.99
Total $ 152.97 Stars icon
Banner background image

Table of Contents

9 Chapters
1. Improving Entity Framework in the Real World Chevron down icon Chevron up icon
2. Mapping Entities Chevron down icon Chevron up icon
3. Validation and Changes Chevron down icon Chevron up icon
4. Transactions and Concurrency Control Chevron down icon Chevron up icon
5. Querying Chevron down icon Chevron up icon
6. Advanced Scenarios Chevron down icon Chevron up icon
7. Performance and Scalability Chevron down icon Chevron up icon
A. Pitfalls Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
(3 Ratings)
5 star 0%
4 star 0%
3 star 33.3%
2 star 33.3%
1 star 33.3%
Felix Aug 26, 2017
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
The book is OK, especially since it emphasizes what is not yet available in EF Core 1. Given the EF Core 2 just hit the market, I expect it to be significantly modified. But that's the fate of any book about fast-changing technology.The book is structured as a list of recipes - Getting Ready; How to do it; how it works; There's more; See also. As result, it looks more like a reference manual than a book. The explanation of what is *it* that is at the center of the recipe is very limited.Second, there is a lot of duplication: Getting Ready is pretty much the same - or at least the same in the chapter. The code without any explanation might as well be just downloaded from the site. And given that the title is EF *Core*, it's strange how many distracting references about how to do things in EF 6.
Amazon Verified review Amazon
Vlad Gâdescu Jul 17, 2017
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
For me the book was hard to follow and not very clear. It has a lot of code examples that are also hard to follow and understand. After every code snippet the writer tries to explain it, but he does it in a very brief and superficial manner. If you want to learn about EF, do not buy this book.
Amazon Verified review Amazon
google007 Mar 27, 2017
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Even doesn't mention how to replace an old object with new one.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.