Beginning Entity Framework Core 2.0: Database Through Domain-Specific Objects and Methods 1st Edition Derek J. Rouleau
Beginning Entity Framework Core 2.0: Database Through Domain-Specific Objects and Methods 1st Edition Derek J. Rouleau
com
https://textbookfull.com/product/beginning-entity-framework-
core-5-from-novice-to-professional-1st-edition-eric-vogel/
textbookfull.com
https://textbookfull.com/product/operative-orthopaedics-2nd-edition-
timothy-wr-briggs/
textbookfull.com
Designing Robot Behavior in Human Robot Interactions 1st
Edition Changliu Liu (Author)
https://textbookfull.com/product/designing-robot-behavior-in-human-
robot-interactions-1st-edition-changliu-liu-author/
textbookfull.com
https://textbookfull.com/product/borderology-cross-disciplinary-
insights-from-the-border-zone-along-the-green-belt-jan-selmer-methi/
textbookfull.com
https://textbookfull.com/product/nutrition-for-health-and-health-care-
linda-kelly-debruyne/
textbookfull.com
https://textbookfull.com/product/pocket-rough-guide-madrid-rough-
guides/
textbookfull.com
Children and Mental Health Talk: Perspectives on Social
Competence Joyce Lamerichs
https://textbookfull.com/product/children-and-mental-health-talk-
perspectives-on-social-competence-joyce-lamerichs/
textbookfull.com
Beginning
Entity Framework
Core 2.0
Database Access from .NET
—
Work directly with data through
domain-specific objects and methods
—
Derek J. Rouleau
Beginning Entity
Framework Core 2.0
Database Access from .NET
Derek J. Rouleau
Beginning Entity Framework Core 2.0
Derek J. Rouleau
East Baldwin, Maine, USA
Introduction�������������������������������������������������������������������������������������������������������������xv
v
Table of Contents
vi
Table of Contents
Chapter 7: Finishing Our ASP.NET MVC .NET Core 2.0 Project������������������������������ 237
Data Validation�������������������������������������������������������������������������������������������������������������������������� 237
Using a Regular Expression to Validate a Property�������������������������������������������������������������� 241
Validating the Rest of Our Models��������������������������������������������������������������������������������������� 243
Adding Column Sorting to Results�������������������������������������������������������������������������������������������� 252
Adding Search Capabilities������������������������������������������������������������������������������������������������������� 256
Adding Pagination: Version 1���������������������������������������������������������������������������������������������������� 262
Adding Paging: Version 2���������������������������������������������������������������������������������������������������������� 270
Grouping Results����������������������������������������������������������������������������������������������������������������������� 275
Summary���������������������������������������������������������������������������������������������������������������������������������� 287
vii
Table of Contents
Index��������������������������������������������������������������������������������������������������������������������� 333
viii
About the Author
Derek J. Rouleau is a Computer and Information Systems Manager for a small company
in the greater Portland, Maine area. He has been working with computers since the mid
1990s thanks to a friend’s father, who got him interested in hardware and the workings
of the operating system. Derek started professionally programming while working for
an educational publishing and software company in the Quality Assurance department.
He has been using Visual Basic since VB 6 and C# since 2010. Although he now manages
the department where he works, Derek still makes time each week to write code and
research new and exciting technologies. When he’s not working, he is involved with Off
Track Standardbreds, and he competes in Dressage.
ix
About the Technical Reviewer
Doug Holland is a Technical Evangelist at Microsoft. Before joining Microsoft in 2010,
he was awarded the Microsoft MVP (C#) and Intel Black Belt Developer awards. He has
presented sessions at the Microsoft BUILD conference and frequently speaks at other
events about Microsoft technologies, from cloud computing to mixed reality. He holds a
Master’s Degree in Software Engineering from Oxford University, as well as certifications
from Microsoft and Unity Technologies. You can follow him on Twitter @dougholland or
connect with him on LinkedIn at https://www.linkedin.com/in/dougholland/.
xi
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Acknowledgments
I would like to thank Jonathan Gennick and Jill Balzano for having the faith in me and
for helping me bring this book to you. If it weren’t for them and all the great people at
Apress, this would not have been possible.
I also need to thank my Uncle “Doc” and Don Rahmlow of TC2 Consulting Services for
reminding me that we always need to keep trying to learn new things and for pushing me
to keep improving myself. As we get along in our careers, we tend to stick with what we
know, but in this industry you need to keep up with the ever-changing environment, which
isn’t always easy.
xiii
Introduction
We decided to try a different approach at writing a technical book, and that is to convey
the information through examples, rather than long paragraphs of text you are only
going to forget later. The hope is that this will give you a good foundation to start your
Entity Framework Core 2.0 journey and that, when you complete the book and start
working on your own projects, you’ll have a good understanding of the material.
Even though this is a book on Entity Framework Core 2.0, we are going to cover some
C# topics that you might not be familiar with, so I hope you find those parts helpful.
In the second part of this book, we cover some aspects of ASP.NET MVC Core. If you
are interested in that topic, Apress has some very good books on the subject. I highly
recommend that you look into them. Although you will have a working web application
by the end, it will behoove you to do some more reading on the subject.
xv
Introduction
Requirements
When writing this book, I did everything in Visual Studio 2017 Preview and SQL Server
2014. The free version of SQL Server and Visual Studio works with all the examples in
this book. Since this is a beginner book, I thought it best to use the tools that someone
just starting might be using. You can use any version of SQL Server 2008 or newer with
Entity Framework Core 2.0; however, you will run into issues when you try to do the
paging examples if you have an older version of SQL Server, so try to use at least version
2014 if at all possible.
Although you do create a web application in the second section of this book, it is not
required that you have a web server. You need one only if you want to deploy the project
or one like it. Otherwise, you can run and test everything through Visual Studio.
Before We Begin
One final note before we begin. I generally try to live my programming life by two of
my favorite quotes. The first is “never remember anything you can look up” which I’m
pretty sure is paraphrased from Albert Einstein. Now I’m not saying that you shouldn’t
remember how to use an int without having to look it up online or in a book. But for
those things that you hardly ever do, don’t take the time to commit them to memory.
The second is “frustration begins where knowledge ends”. This quote I know for sure is
from Clinton Anderson. This is by far the hardest to implement. If you are getting frustrated
xvi
Introduction
with something, take a step back and try to figure out why. If you are honest with
yourself, it’s probably because you have run out of knowledge on the subject. Try to
figure out where the problem is and which part you are missing. Then learn about it and
try again. By doing this, you will likely have more success than just plugging away and
blindly trying different things.
xvii
CHAPTER 1
Getting Started
We are going to jump right into an example, as I think that is the best way to learn
something. As we cover new topics, we explain them as we work on them. This is better
than a general overview at the start of the chapter or section, because that won’t mean
much to you while you are reading it. I personally dislike it when books show you the
wrong way of doing something and then show you how to do it “correctly” after you just
spent five minutes typing in the wrong way, so I’m not going to do that to you. However,
I do explain why we are doing something and explain what would be wrong. Since this is
a “getting started” type of book, all the examples work as written, although they may not
be the best way of getting it done. As you get more comfortable with this technology and
as your skills grow, you’ll come up with your own way of doing things. I’m just here to
help you started down the path to greatness.
For those of you who are like me and skipped the Introduction, you should be using
the latest build of Visual Studio 2017 and at least .NET Framework 4.6.1. At the time of
this writing, the latest build of Visual Studio was 15.3.3 with the .NET Framework build
4.7.02046. These build numbers can be found in the Visual Studio About window.
1
© Derek J. Rouleau 2018
D. J. Rouleau, Beginning Entity Framework Core 2.0, https://doi.org/10.1007/978-1-4842-3375-7_1
Chapter 1 Getting Started
The application created here is used throughout the first section of this book and
each section builds off the last, so you really can’t skip around. With that being said, let’s
get started!
2
Chapter 1 Getting Started
• Microsoft.EntityFrameworkcore.SqlServer v2.0.0
• Microsoft.EntityFrameworkcore.Tools v2.0.0
• Microsoft.EntityFrameworkcore.SqlServer.Design v2.0.0
Note As of the writing of this book, only the preview packages were available.
If you can’t find version 2.0.0, check the preview packages.
Figure 1-2 shows what it looks like when you search for a package. Once you have
selected the package you want to install, just click on the Install button to the right and
click I Accept for any prompts that come up.
That completes the basic setup of your application. Feel free to save your work before
you continue.
Core. Later in the book, we use an application that is database-first, so you can see the
difference. If you were to create an application based on an existing database, database-
first is the choice you’d probably use.
We are going to follow the model that is generally used by most people who design
websites, so we need to create two folders in our application—Models and Data. If you
have never done this before, it’s simple. Just right-click on the ComputerInventory
project in the Solution Explorer and select Add and then New Folder. Then change the
name to Models. See Figure 1-3. Each of our eventual tables will have a corresponding
class file in the Models folder. I’ll take you step by step through the first one and then you
should be able to create the remaining ones on your own (you just change the name of
the class).
4
Chapter 1 Getting Started
Let’s create our first class file. Right-click on the Models folder, select Add, and
then select Class (should be at the bottom of the list). Make sure that Class is selected
and change the name to OperatingSys.cs. Figure 1-4 shows you what it should look
like when you are creating the new class file. We are using OperatingSys rather than
OperatingSystem, as OperatingSystem is a reserved type in C# and we’d have to put
Models.OperatingSystem in our code each time we wanted to use it.
5
Chapter 1 Getting Started
Once you click on Add, OperatingSys.cs will be created and load for you to start
working on it. Listing 1-1 shows the code for this new class.
using System;
using System.Collections.Generic;
namespace ComputerInventory.Models {
public partial class OperatingSys {
public OperatingSys() {
Machine = new HashSet<Machine>();
}
The first thing you need to remember is to make the class public so it will be
accessible throughout the application. What we have done here is created the basis
for the first table in that database, which we will call OperatingSys. In your table, it’s a
good idea to have an ID field that is normally a primary key, and we have done that with
OperatingSysID. You should have two errors, both telling you the same thing, that the
type or namespace name Machine could not be found. That is correct, as you haven’t
added them yet, so you can ignore this for now.
Two things should hopefully jump out at you. We have created a constructor for our
class and within that, we have created a new HashSet<Machine> called Machine. You
don’t need to use a HashSet<T> here, but you do need to use a collection and since that is
the default for EF Core we are going to stick with it for our examples.
If you are more familiar with EF Core and have the time, I highly recommend looking
at the other set types as there are cases in which using a HashSet isn’t needed and there is
a better fit. We then have our ICollection<Machine>, which provides an interface to the
Machine table. After all, one OS could have multiple machines, but one machine generally
only has one OS (we aren’t going to handle multi-boot systems in this simple example).
6
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Chapter 1 Getting Started
For a simple class like this, that is all there is to it. We will set up all of our tables that
don’t have any linking via foreign keys first.
Now create the next class and call it MachineType. Listing 1-2 shows all the code you
need to create the class.
using System;
using System.Collections.Generic;
namespace ComputerInventory.Models {
public partial class MachineType {
public MachineType() {
Machine = new HashSet<Machine>();
}
As you can see, this is very similar to the OperatingSys class. We have one basic class
left, the WarrantyProvider class. Its code is shown in Listing 1-3.
namespace ComputerInventory.Models {
public partial class WarrantyProvider {
public WarrantyProvider() {
MachineWarranty = new HashSet<MachineWarranty>();
}
7
Chapter 1 Getting Started
There are a couple of things with this class that you need to be aware of. First of
all, the SupportNumber property is a string. This was done so that we can limit the
number of characters to 10 (this is the number of digits that United States telephone
numbers have; if you need to add a number from another country, this may need to be
increased). We will take care of the field length in a little bit. SupportExtension is not
required, as you could have a direct number to support and thus no value here, so we
add the question mark after int to make it nullable (int?). You should have two new
errors about MachineWarranty, but they will go away soon, so you can ignore those
as well. If you were going to put this into production, you could increase the length of
the ProviderName, as you may have a support contract with a company such as “Bob’s
Computer Repair Service of Northern California,” which would not fit into a 30-character
field.
Now for the first class that has a foreign key in it. Listing 1-4 shows the code for
Machine.cs, which will be the “base class” for most of what you’ll be working on in this
project.
using System;
using System.Collections.Generic;
namespace ComputerInventory.Models {
public partial class Machine {
public Machine() {
SupportTicket = new HashSet<SupportTicket>();
}
8
Chapter 1 Getting Started
The first three quarters of this code contains all things that you have already seen,
except for the new error for SupportTicket. Then we get to public int OperatingSysId
{ get; set; }. In and of itself, there isn’t anything special about it, until you realize that
we created a property called OperatingSysId in the OperatingSys class. You then see
the line public OperatingSys OperatingSys { get; set; } at the bottom, and this
is what makes all the difference. Hopefully up until now, you have been wondering why
we haven’t specified which field is the primary key. That is because Entity Framework
Core is nice enough to do it if it’s obvious enough, plus we’ll be doing a bit more with
our database fields when we set up our DBContext class, but we are getting ahead of
ourselves. As you’ll see later, specifying the primary key is good practice for making your
code easier to read and for maintainability purposes. The first property we created in
each class so far has the name ID in it. Well, the great folks at Microsoft added logic that
gives EF the ability to pick the most logical choice for the key.
Now that makes sense for the first part, but what about for OperatingSysId? How
is it to know that we want that to be a foreign key? Well, that second line tells EF that we
are going to be adding a reference to the OperatingSys class/table and it assumes that
you want to link it with the OperatingSysId field to create the foreign key. I strongly
encourage you to look into this further if you aren’t going to create your tables in SQL
Server Management Studio or another DBMS, because a good table structure is like a
foundation; the stronger it is, the better it will perform/hold up.
9
Chapter 1 Getting Started
The code for the three remaining tables you need to create are shown in Listings 1-5,
1-6, and 1-7.
using System;
using System.Collections.Generic;
namespace ComputerInventory.Models {
public partial class MachineWarranty {
public int MachineWarrantyId { get; set; }
public string ServiceTag { get; set; }
public DateTime WarrantyExpiration { get; set; }
public int MachineId { get; set; }
public int WarrantyProviderId { get; set; }
using System;
using System.Collections.Generic;
namespace ComputerInventory.Models {
public partial class SupportTicket {
public SupportTicket() {
SupportLog = new HashSet<SupportLog>();
}
10
Chapter 1 Getting Started
using System;
using System.Collections.Generic;
namespace ComputerInventory.Models {
public partial class SupportLog {
public int SupportLogId { get; set; }
public DateTime SupportLogEntryDate { get; set; }
public string SupportLogEntry { get; set; }
public string SupportLogUpdatedBy { get; set; }
public int SupportTicketId { get; set; }
Now you have what you need to start creating the seven tables used in this first section
of the book. As I mentioned, each class created in the Models folder represents a table in
the database. The next thing we need to do is set up our DBContext, which is the Grand
Poobah of Entity Framework and Entity Framework Core. It’s the connection between
your entity classes and the database. Without this primary class, we wouldn’t have Entity
Framework and we’d be back to setting up database connections using the SQL client and
creating instances of the DataSet and DataTables classes while putting things in memory
and using lots of big SQL queries. You’ll see better how great it is once you use it.
Since we are talking about DBContext, let’s create a Context class so we can get to
writing some code to interact with our database that much quicker. Remember that
folder we created called Data? That is where we are going to put our class, so create a
new class in the Data folder and call it MachineContext.cs. Listing 1-8 shows the code
we’ll use for MachineContext.cs. You could have called this class anything you wanted
and you’ll want to give it a name that makes sense to you when you create your own
projects. Okay, this is going to be a big one, so get ready.
11
Random documents with unrelated
content Scribd suggests to you:
V LUKU.
Vastausta ei kuulunut.
"Kuuletteko", pauhasin.
"Mitä?"
"Ei kukaan."
"Willy sen heitti", vastasi Toddy niin epäselvällä äänellä, että oli
aivan ilmeistä, että veljen käsi raskaana lepäsi pienellä huuliparilla.
"Minä."
Sunnuntai-iltapäivä.
"Willy", sanoin minä, "mitä teette sunnuntaisin, kun isä ja äiti ovat
kotona? Mitä he lukevat ja mistä he puhuvat teille?"
"Ja mitä?"
"Ei Toddy", väitteli Willy vastaan. "Joosefin viitta oli aivan yhtä
verinen kuin Goljatin pää." Sitten Willy kääntyi minuun ja selitti, että
"siksi Toddy pitää Goljatista, kun hänen päänsä oli yltäyleensä
verinen, kun se katkaistiin." Ja Toddy — tuo henkiolento, jota äidin
sanojen mukaan kaikki kaunis vastustamattomasti veti puoleensa —
Toddy katsoa tuijotti minuun kuten teurastajapoika katsoo
kuolemaantuomittua lammasta ja huomautti:
"Goljatin pää oli aivan vejinen ja Davidin miekka oli aivan vejinen,
aivan vejinen, niin vejinen kuin, kuin kaikki."
"Joosef oli hyvä, pieni poika, jota hänen isänsä hellästi rakasti.
Mutta veljet eivät pitäneet hänestä. Ja he myivät hänet Egyptiin. Ja
hän oli hyvin viisas ja selitti ihmisille, mitä heidän unensa merkitsivät
ja niin tuli hänestä kuuluisa mies. Ja hänen veljensä tulivat Egyptiin
ostamaan viljaa ja Joosef möi heille, ja sitten hän ilmaisi heille
itsensä. Ja hän lähetti heidät kotiin hakemaan isää Egyptiin ja sitten
he elivät siellä kaikki yhdessä."
"Harry eno", sanoi Willy, "mitä luulet että minun isäni tekisi, jos
hän luulisi, että leijona söisi minut suuhunsa? Minä luulen, että hän
itkisi kauheasti, etkö sinäkin? Kerro nyt meille toinen kertomus — tai
minäpäs tiedän — lue meille —."
"No", sanoi Toddy. "Goljat oli pitkä, tuuji miet, ja David oli hyvin
pieni miet, ja Goljat tanoi 'Tule tänne niin minä työn tinut' ja David
tanoi 'En minä tinua pelkää.' Titte David pitti viiti pientä kiveä linkoon
ja pyyti Jumalalta apua, ja antoi lingon paitkata kivet Goljatin tiimiin
ja tappaa hänet aivan kokonaan, ja David otti Goljatin miekan ja löi
Goljatin pään poikki ja te tuli aivan vejitekti, ja Goljat juokti
tiehentä." Tätä lyhyttä kertomusta säesti suurempi määrä vilkkaita ja
yllättäviä eleitä, kuin mitä hillitty kaunopuhuja Gough milloinkaan
tuhlaa pitkään puheeseen.
"Minusta ei ole ollenkaan hauskaa kuulla Goljatista", sanoi Willy.
"Minä tahtoisin kuulla Feruksesta."
"Kenestä?"
"Ohhoh", ihmetteli Willy, "eikö sinulla ollut isää, kun olit pieni?"
"Hän tahtoo, että laulaisit laulun Kalle pojasta" sanoi Willy. "Hän
tahtoo, että äiti laulaa sen hänelle aina, kun hän on satuttanut
itsensä ja sitten hän lakkaa itkemästä."
"Minä sanon, kuinka se on", sanoi Willy, ja tuo nuori mies lauloi
seuraavan laulun, säkeen kerrallaan, minä kerraten sanat ja
säveleen:
"Pidän."
"Harry eno", sanoi Willy, "Jumala oli hyvä, kun antoi sinun olla
kanssamme, muutoin Toddy olisi hukkunut."
"Oi, minä pidän hänestä", sanoi Willy. "Hän on niin sievä ja soma
— aivan kuin leivos — aivan kuin hän maistuisi hyvälle — oi, minä
rakastan häntä niin, etkö sinäkin?"
"Hän tahtoo, että Harry eno laulaisi hänelle laulun, joka alkaa:
'Ken tietää, minne joutunut'", ilmoitti Willy. "Hän tahtoo että tätä
laulua lauletaan aina, kun hän on jollakin tavoin satuttanut itsensä."
"Laula kovemmin."