39,59 €
Being able to create and maintain data-oriented applications has become crucial in modern programming. This is why Microsoft came up with Entity Framework so architects can optimize storage requirements while also writing efficient and maintainable application code. This book is a comprehensive guide that will show how to utilize the power of the Entity Framework to build efficient .NET Core applications. It not only teaches all the fundamentals of Entity Framework Core but also demonstrates how to use it practically so you can implement it in your software development.
The book is divided into three modules. The first module focuses on building entities and relationships. Here you will also learn about different mapping techniques, which will help you choose the one best suited to your application design. Once you have understood the fundamentals of the Entity Framework, you will move on to learn about validation and querying in the second module. It will also teach you how to execute raw SQL queries and extend the Entity Framework to leverage Query Objects using the Query Object Pattern. The final module of the book focuses on performance optimization and managing the security of your application. You will learn to implement failsafe mechanisms using concurrency tokens. The book also explores row-level security and multitenant databases in detail.
By the end of the book, you will be proficient in implementing Entity Framework on your .NET Core applications.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 278
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: December 2017
Production reference: 1141217
ISBN 978-1-78829-413-3
www.packtpub.com
Author
Prabhakaran Anbazhagan
Copy Editor
Safis Editing
Reviewers
Jason De Oliveira
Alvin Ashcraft
Project Coordinator
Prajakta Naik
Commissioning Editor
Merint Mathew
Proofreader
Safis Editing
Acquisition Editor
Chaitanya Nair
Indexer
Francy Puthiry
ContentDevelopmentEditor
Lawrence Veigas
Graphics
Jason Monteiro
Technical Editor
Tiksha Sarang
Production Coordinator
Deepika Naik
Prabhakaran Anbazhagan is a Microsoft Solution Architect living in Chennai, India. His passion for programming started while creating a website for his school, and that's where the never-ending journey started. He became the secretary of a technology group in college, creating websites yet again, automating symposiums, and much more.
He started his career at a prestigious product-based company; his knowledge was respected and recognized by his seniors, who let him develop tools and automation to sharpen his talents. Lucky guy! People hardly ever get to nurture their talent, but he got a handful of opportunities to sharpen his skills and become a Solution Architect, becoming a jack of all trades but still an expert in .NET.
Prabhakaran has more than 12 years of IT experience in architecting, designing, and developing mission-critical desktop, web, and mobile applications. He has experience in full-stack development spanning ASP.NET MVC, Web API, C#, Mobility expert in Swift, Objective-C, Blackberry Cascades, hybrid apps, SharePoint, JavaScript, jQuery, and MEAN.JS.
Jason De Oliveira works as a CTO for MEGA International (http://www.mega.com), a software company in Paris (France), providing modeling tools for business transformation, enterprise architecture, and enterprise governance, risk, and compliance management. He is an experienced manager and senior solutions architect, with high skills in software architecture and enterprise architecture.
He loves sharing his knowledge and experience via his blog, speaking at conferences, writing technical books, writing articles in the technical press, giving software courses as MCT, and coaching co-workers in his company. He frequently collaborates with Microsoft and can often be found at the Microsoft Technology Center (MTC) in Paris.
Microsoft has awarded him for more than 6 years with the Microsoft® Most Valuable Professional (MVP C#/.NET) award for his numerous contributions to the Microsoft community. Microsoft seeks to recognize the best and brightest from technology communities around the world with the MVP Award. These exceptional and highly respected individuals come from more than 90 countries, serving their local online and offline communities and having an impact worldwide.
Feel free to contact him via his blog if you need any technical assistance or want to talk about technical subjects (http://www.jasondeoliveira.com).
Jason has worked on the following books:
.NET 4.5 Expert Programming Cookbook
(English)
WCF 4.5 Multi-tier Services Development with LINQ to Entities
(English)
.NET 4.5 Parallel Extensions Cookbook
(English)
WCF Multi-layer Services Development with Entity Framework
(English)
Visual Studio 2013: Concevoir, développer et gérer des projets Web,
les
gérer
avec
TFS 2013
(French)
Alvin Ashcraft is a software developer living near Philadelphia, PA. He has dedicated his 22-year career to building software with C#, Visual Studio, WPF, ASP.NET, HTML/JavaScript, UWP, and Xamarin apps and SQL Server. He has been awarded as a Microsoft MVP nine times; once for Software Architecture, seven times for C# and Visual Studio & Tools, and for Windows Dev in 2018-2019. You can read his daily links for .NET developers on his blog at alvinashcraft.com and UWP App Tips blog at www.uwpapp.tips.
He currently works as a Principal Software Engineer for Allscripts, developing clinical healthcare software. He has previously been employed with several large software companies, including Oracle, Genzeon, and Corporation Service Company. There, he helped create software solutions for financial, business, and healthcare organizations using Microsoft platforms and solutions.
He was a technical reviewer for NuGet 2 Essentials and Mastering ASP.NET Core 2.0 by Packt.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788294130.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Kickstart - Introduction to Entity Framework Core
Prerequisites
Creating a new project
The Start page
The File menu
Structuring the web app
Installing Entity Framework
Data models
Blog entity
Post entity
Database context
Registering the context in services (.NET Core DI)
Creating and seeding databases
CRUD operations
Summary
The Other Way Around – Database First Approach
Preparing the database
Blog entity script
Post entity script
Creating new project
Installing Entity Framework
Reverse engineering the database
Configuring data context
Working with the Blog entity
Working with the Post entity
Registering context in services (.NET Core DI)
Refactoring the OnConfiguring() method
Refactoring the ConfigureServices method
The appsettings.json setting
Performing CRUD operations
Creating controller action
Edit controller action
The Delete view
Summary
Relationships – Terminology and Conventions
Understanding relationship terms
Data models
Blog entity
The Post entity
Principal entity
Principal key
Dependent entity
Foreign key
Navigation property
Collection navigation property
Reference navigation property
Inverse navigation property
Conventions in a relationship
Fully-defined relationships
Fully-defined relationships - under the hood
No foreign key property
No foreign key property - under the hood
Single navigation property
Foreign key
Inverse property
Summary
Building Relationships – Understanding Mapping
Relationships
The one-to-one relationship
Building one-to-one relationships using the Fluent API
The one-to-many relationship
The many-to-many relationship
Building many-to-many relationship using the Fluent API
Fluent API
Identifying navigation property and inverse navigation
Identifying the single navigation property
Relationship-building techniques
Building relationship using a foreign key
Building relationships using a principal key
Building relationships using the IsRequired method
Cascade delete
Data migration issue with EF Core 2.0
Summary
Know the Validation – Explore Inbuilt Validations
Diving into built-in validations
Required field validation
Incorporating the Required validation in blogging system models
EmailAddress field validation
Incorporating EmailAddress validation in blogging system models
Compare field validation
Incorporating the Compare validation in blogging system models
Url field validation
Incorporating Url validation in blogging system models
MinLength field validation
MaxLength field validation
RegularExpression field validation
Summary
Save Yourself – Hack Proof Your Entities
Client-side validation
Validating data without client-side scripting
Server-side validation
Manual validation
Custom validation
Creating client-side logic for custom validation
Remote validation
Summary
Going Raw – Leveraging SQL Queries in LINQ
Basic raw SQL queries
Building parameterized queries
Composing with LINQ
Executing SQL query without a DBSet or POCO
Summary
Query Is All We Need – Query Object Pattern
Introduction to query objects
Improving repositories with the query object pattern
Introduction to repositories
Solution to the repository assignment
Incorporating the query object pattern into repositories
List query object support in the repository
Single query object support in the repository
Solution to the repository with the queries assignment
Composing queries with commands
Solution to the command queries assignment
Enhancing queries with expression trees
Solution to the expression trees assignment
Summary
Fail Safe Mechanism – Transactions
Default behavior of a transaction
Adding tags support in the blogging system
Leveraging default transaction behavior
Creating a simple transaction
Creating a cross-context transaction
File upload support to the blogging system
Limitations to the transaction scope
Custom transaction scope support
Adding date picker support to the blogging system
Leveraging transactions between multiple technologies
Recent posts support to the blogging system
Anonymous posts list and individual blog post
Listing comments
Adding comments using external database transactions
Summary
Make It Real – Handling Concurrencies
Handling concurrency in EF
Understanding the concurrency conflicts
Optimistic concurrency
Pessimistic concurrency
Introducing concurrency tokens
Non-timestamp based concurrency tokens
Configuring non-timestamp tokens through data annotation
Configuring non-timestamp tokens through Fluent API
Timestamp-based concurrency tokens
Configuring timestamp tokens through data annotation
Configuring timestamp tokens through Fluent API
Handling concurrency conflicts
Applying optimistic concurrency
Database wins
Client wins
User-specific custom resolution
Applying pessimistic concurrency
Summary
Performance – It's All About Execution Time
The AsNoTracking() method
How does tracking work?
No-tracking queries
Projections
Detecting changes
Asynchronous operations
Transactions leveraging asynchronous operations
Unnecessary volume returned
The N+1 Select problem
More data than required
Mismatched data types
Missing indexes
Summary
Isolation – Building a Multi-Tenant Database
Authentication in the blogging system
Row-Level Security
Filter predicate
Block predicate
Multi-tenancy
Standalone
Database-per-tenant
Shared multi-tenant
Dive into multi-tenancy
Blocking cross-tenant write operation
Summary
Being able to create and maintain data-oriented applications has become crucial in modern programming. This is why Microsoft came up with Entity Framework (EF), so architects can optimize storage requirements while also writing efficient and maintainable application code. This book is a comprehensive guide that will show you how to utilize the power of the EF to build efficient .NET Core applications. It not only teaches all the fundamentals of EF Core, but also demonstrates how to use it practically so you can implement it in your software development. This book is divided into three modules. The first module focuses on building entities and relationships. Here, you will also learn about different mapping techniques, which will help you choose the one best suited to your application design. Once you have understood the fundamentals of EF, you will move on to learn about validation and querying in the second module. It will also teach you how to execute raw SQL queries and extend the EF to leverage Query Objects using the Query Object Pattern. The final module of the book focuses on performance optimization and managing the security of your application. You will learn to implement fail-safe mechanisms using concurrency tokens. The book also explores row-level security and multitenant databases in detail. By the end of the book, you will be proficient in implementing EF on your .NET Core applications.
Chapter 1, Kickstart – Introduction to Entity Framework Core, teaches you about installing/configuring Entity Framework Core in .NET Core applications. It guides us through performing CRUD (Create/Read/Update/Delete) operations.
Chapter 2, The Other Way Around – Database First Approach, explains about reverse engineering and existing database using EF Core. It guides us through performing migrations and also helps us in retaining model changes that won't be lost during migrations.
Chapter 3, Relationships – Terminology and Conventions, provides knowledge about relationship terms related to entities, keys, and properties. We will also see different conventions available with respect to relationships.
Chapter 4, Building Relationships – Understanding Mapping, helps you explore multiple relationship techniques and explains how to leverage them in your application design. We will also explore how to create relationships using Fluent API.
Chapter 5, Know the Validation – Explore Inbuilt Validations, teaches you about how validation works in the framework, explores built-in validations, shows how they should be configured, covers the patterns each validation expects from the user, and shows how the validation error is rendered by the MVC engine.
Chapter 6, Save Yourself – Hack Proof Your Entities, helps us with adding validations, explains why we need validations on both the client side and server side, and shows how to achieve it. It also introduces custom validation, and how to create client-side logic for validation and remote validation.
Chapter 7, Going Raw – Leveraging SQL Queries in LINQ, teaches you about executing Raw SQL Queries while also teaching you how to execute parameterized queries, compose with LINQ, and, finally, execute without a DbSet or POCO object.
Chapter 8, Query Is All We Need – Query Object Pattern, helps you understand the Query Object pattern, and extend EF to leverage query objects.
Chapter 9, Fail Safe Mechanism – Transactions, helps you understand the existing behavior of transactions, how to create regular/cross-context transactions, and how to use external DBTransactions.
Chapter 10, Make It Real – Handling Concurrencies, elaborates on how concurrency is wired in EF and how to handle it. It explains concurrency tokens in detail and shows how to create a fail-safe mechanism using it.
Chapter 11, Performance – It's All About Execution Time, teaches you how to improve EF's performance by properly utilizing the framework, reducing abuses, and much more.
Chapter 12, Isolation – Building a Multi-Tenant Database, explores row-level security and multi-tenant databases in detail.
To work with this text, we assume you are familiar with .NET Core and C#.
You require the following tools to successfully execute the code in this book:
Visual Studio 2017 Express
SQL Server 2017 Express
SQL Server 2017 Developer
This book is for .NET Core developers who would like to integrate EF Core in their application. Prior knowledge of .NET Core and C# is assumed.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in a text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, and user input are shown as follows: "The new column should be included in the Edit method of PostController."
A block of code is set as follows:
public interface IPostDetailQueryHandler { Task<Post> Handle(PostDetailQuery query); }
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
public async Task<IActionResult> Index() { return View(await _context.Blogs
.FromSql("Select * from dbo.Blog")
.ToListAsync()); }
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "We can see from the following screenshot that the Url value is unchanged."
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-Entity-Framework-Core. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/MasteringEntityFrameworkCore20_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
I still remember the days when we were spending quite a lot of time on working with relational databases rather than just focusing on solving business problems; those days are definitely gone. To elaborate, let's jot down the issues we had before ORM:
Data access layers were not portable, which made it hard to change from one platform to another.
There were no abstractions, which forced us to write manual mapping between objected-oriented objects and data entities.
Vendor-specific SQL statements, which requires k
no
wledge to port between different RDBMS systems.
Relied heavily on triggers and stored procedures.
The entire product development process shifted towards tools and open source platforms, and even Microsoft took that path from .NET Core onward. If we keep spending time on writing code which could be achieved through tools, we might end up looking like cavemen.
The Entity Framework was created to address this concern; it was not introduced with the initial .NET framework but rather was introduced in .NET Framework 3.5 SP1.
If we look closely, it was obvious that the .NET team built it for the following reasons:
To minimize the time spent by the developers/architects on stuff like abstractions and the portable data access layer
So that the developers do not require vendor specific SQL knowledge
So that we can build object-oriented business logic by eradicating triggers and SPs
We will cover the following topics here:
Prerequisites
Creating a new project
Installing Entity Framework 2.0
Data models
Database context
Registering the context in services (.Net Core DI)
Creating and seeding databases
Performing CRUD operations
.NET Core, the open source platform, paved the way for multi-platform support in Visual Studio 2017. The editors came in different flavors, supporting both platform-specific and cross-platform IDEs:
Visual Studio
: An e
xclusive edition for Windows with Community, Professional and Enterprise editions:
Visual Studio 2017 IDE can be downloaded directly from https://www.visualstudio.com.
Visual Studio for Mac
: An e
xclusive edition for macOS, which was actually inherited from
Xamarin Studio (Xamarin was acquired by Microsoft):
Visual Studio for Mac can be downloaded from https://www.visualstudio.com/vs/visual-studio-mac/.
Visual Studio Code
: The c
ross-platform editor from Microsoft for Windows, Linux, and macOS:
Download the desired version/edition of Visual Studio Code from https://www.visualstudio.com/downloads/.
The Visual Studio 2017 installer is segregated into workloads, individual components, and language packs. We will be installing and using Visual Studio Community 2017 with the workloads ASP.NET and web development and .NET Core cross-platform development. The workload is a combination of one or more individual components which can also be installed from the Individual components tab of the installer, as follows:
We have looked at the different flavors/editions of Visual Studio available to us, and we will be using Visual Studio Community on our journey, which is free of charge for private and test purposes. It is up to the reader to pick an edition which suits their needs (the tools and scaffolding available in the IDE might differ).
Open Visual Studio and create a new project either from the File menu or from the Start page.
From the New Project section, create a new project using any one of the following approaches:
Select
Create new project...
. On the left pane, select
Templates
|
Visual C#
|
.NET
C
ore
. Select the
ASP.NET Core Web Application
template from the list.
Search the project templates for the
ASP.NET Core Web Application
and select it. As displayed in the following screenshot, e
nter
MasteringEFCore.Web
as the
Name
and
MasteringEFCore
as
the
Solution name
and click
OK
:
From the File menu, perform the following steps:
Select
New
|
Project
.
On the left pane,
s
elect
Templates |
Visual C#
|
.NET Core
.
Select the
ASP.NET Core Web Application
template from the list.
As displayed in the previous screenshot, enter
MasteringEFCore.CodeFirst.Starter
as the
Name
and
MasteringEFCore
as the
Solution name
and click
OK
.
Irrespective of the previous two approaches, the selected template will provide New ASP.NET Web Application (.NET Core) dialog, to let us choose from the following:
Empty
Web API
: Creates a Web API project
Web Application (Model-View-Controller)
: C
reates an
MVC Web application which also allows us to create APIs
We will be selecting Web Application (Model-View-Controller) from the dialog as shown here:
In our case, select
.NET Core
,
ASP.NET Core 2.0
, and the
Web Application (Model-View-Controller)
template, and also keep the Authentication set to
No Authentication
. Click
OK
:
The generated web application displays a tabbed interface which is new to us (instead of displaying index.cshtml). It allows us to access documentation, connect to any service or even decide on publishing options right from the start page.
I know getting into MVC would be a little outside of the scope of this chapter, but let's dig into a few details before we deep dive into the Entity Framework.
A .NET Core web application is composed of the following folders:
Dependencies
: SDK, server, and client-side dependencies
wwwroot
: All static resources should reside here
Connected Services
: To connect external services available in Marketplace
launchSettings.json
: Settings required to launch a web application
appSettings.json
: Configurations such as logging and connection strings
bower.json
: Client-side dependencies should be configured here
bundleConfig.json
: Bundling is moved to the JSON configuration now
Program.cs
: Everything starts from
Main()
and any program can be made into a web application using the
WebHostBuilder
API
Startup.cs
: For adding and configuring startup services like MVC support, logging, static files support and so on
Controllers
,
Views
: Part of MVC and contains actions and corresponding views
The structure we had discussed so far is illustrated in the following screenshot:
The following highlighted sections in Views\Shared\_Layout.cshtml should be modified with the desired application name:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <
title
>
@
ViewData[
"Title"
] -
MasteringEFCore.Web
</
title
> ... </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> ... <a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">
MasteringEFCore.Web
</a> ... <div class="container body-content"> ... <footer> <p>© 2017 -
MasteringEFCore.Web
</p> </footer> ... </body>
We have created a .NET Core web application with no authentication and explored the structure of the project, which might help us understand MVC in .NET Core. If we expand the dependencies, it is evident that we don't have built-in support for Entity Framework (EF) Core. We will look at the different ways of identifying and installing the packages.
The Entity Framework package should be installed as part of the NuGet package, and can be done in the following ways:
Go to the
Package Manager Console
(
Tools
|
NuGet Package Manager
|
Package Manager Console
), select the project where the package should be installed:
Add the following command in the PM Console to install the package on the selected project:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Go to the
Package Management
tab (either from
Tools
or from
Dependencies/Project
).
For a solution-wide installation,
and availability for all projects that are part of the solution, go to
Tools
|
NuGet Package Manager
|
Manage NuGet
Packages for Solution...
or right-click on the solution from
Solution Explorer
and select
Manage NuGet Packages for Solution...
For project wise installation, right-click on
dependencies
from the
desired
project or right-click on the desired project and select
Manage NuGet Packages...
Search for
Microsoft.EntityFrameworkCore.SqlServer
, select the stable version
2.0.0
and install the package. It contains all the dependent packages as well (key dependencies such as
System.Data.SqlClient
and
Microsoft.EntityFrameworkCore.Relational
):
We have looked at different ways of using the Package Manager console so far, and installed packages related to EF Core. In the next section, we will start building the schema and later consume the created entities using EF.
When we think about creating data models in the .NET world way before creating the database, we are a little bit off the legacy track, and yes, it's been widely called the Code-First approach. Let's create entity classes using code-first for the Blogging application, and put them into the Models folder under the project.
Create a Blog.cs class file and include the following properties:
publicclass
Blog
{
public
int
Id {
get
;
set
; }
public
string
Url {
get
;
set
; }
public
ICollection
<
Post
> Posts {
get
;
set
; } }
The Entity Framework will look for any property with the name Id or TypeNameId and marks them as the primary key of the table. The Posts property is a navigation property which contains Post items related to this Blog entity. It doesn't matter whether we use ICollection<T> or IEnumerable<T> for the navigation property, EF will create a collection for us, HashSet<T> by default. We could also create a concrete collection using List<T>.
Create a Post.cs class file and include the following properties:
publicclass
Post
{
public
int
Id {
get
;
set
; }
public
string
Title {
get
;
set
; }
public
string
Content {
get
;
set
; }
public
DateTime
PublishedDateTime {
get
;
set
; }
public
int
BlogId {
get
;
set
; }
public
Blog
Blog {
get
;
set
; } }
The BlogId property is a foreign key created for the corresponding Blog
