0% found this document useful (0 votes)
9 views

Beginning Entity Framework Core 2.0: Database Access from .NET - Work directly with data through domain-specific objects and methods 1st Edition Derek J. Rouleau - Get the ebook instantly with just one click

The document provides information about various eBooks related to Entity Framework Core and .NET programming, including titles, authors, and links for downloading. It features a collection of resources for both beginners and professionals, covering topics such as database access, programming techniques, and modern web development. The document also includes details about the author and the structure of one specific book, 'Beginning Entity Framework Core 2.0' by Derek J. Rouleau.

Uploaded by

opriskrapez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Beginning Entity Framework Core 2.0: Database Access from .NET - Work directly with data through domain-specific objects and methods 1st Edition Derek J. Rouleau - Get the ebook instantly with just one click

The document provides information about various eBooks related to Entity Framework Core and .NET programming, including titles, authors, and links for downloading. It features a collection of resources for both beginners and professionals, covering topics such as database access, programming techniques, and modern web development. The document also includes details about the author and the structure of one specific book, 'Beginning Entity Framework Core 2.0' by Derek J. Rouleau.

Uploaded by

opriskrapez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Explore the full ebook collection and download it now at textbookfull.

com

Beginning Entity Framework Core 2.0: Database


Access from .NET - Work directly with data through
domain-specific objects and methods 1st Edition
Derek J. Rouleau
https://textbookfull.com/product/beginning-entity-framework-
core-2-0-database-access-from-net-work-directly-with-data-
through-domain-specific-objects-and-methods-1st-edition-
derek-j-rouleau/

OR CLICK HERE

DOWLOAD EBOOK

Browse and Get More Ebook Downloads Instantly at https://textbookfull.com


Click here to visit textbookfull.com and download textbook now
Your digital treasures (PDF, ePub, MOBI) await
Download instantly and pick your perfect format...

Read anywhere, anytime, on any device!

Modern Data Access with Entity Framework Core: Database


Programming Techniques for .NET, .NET Core, UWP, and
Xamarin with C# 1st Edition Holger Schwichtenberg
https://textbookfull.com/product/modern-data-access-with-entity-
framework-core-database-programming-techniques-for-net-net-core-uwp-
and-xamarin-with-c-1st-edition-holger-schwichtenberg/
textbookfull.com

Modern Data Access with Entity Framework Core: Database


Programming Techniques for . NET, . NET Core, UWP, and
Xamarin with C# 1st Edition Holger Schwichtenberg
https://textbookfull.com/product/modern-data-access-with-entity-
framework-core-database-programming-techniques-for-net-net-core-uwp-
and-xamarin-with-c-1st-edition-holger-schwichtenberg-2/
textbookfull.com

Beginning Entity Framework Core 5: From Novice to


Professional 1st Edition Eric Vogel

https://textbookfull.com/product/beginning-entity-framework-
core-5-from-novice-to-professional-1st-edition-eric-vogel/

textbookfull.com

C 8 0 and NET Core 3 0 Modern Cross Platform Development


Build applications with C NET Core Entity Framework Core
ASP NET Core and ML NET using Visual Studio Code 4th
Edition Mark J. Price
https://textbookfull.com/product/c-8-0-and-net-core-3-0-modern-cross-
platform-development-build-applications-with-c-net-core-entity-
framework-core-asp-net-core-and-ml-net-using-visual-studio-code-4th-
edition-mark-j-price/
textbookfull.com
Practical Entity Framework: Database Access for Enterprise
Applications 1st Edition Brian L. Gorman

https://textbookfull.com/product/practical-entity-framework-database-
access-for-enterprise-applications-1st-edition-brian-l-gorman/

textbookfull.com

Pro Entity Framework Core 2 for ASP.NET Core MVC Adam


Freeman

https://textbookfull.com/product/pro-entity-framework-core-2-for-asp-
net-core-mvc-adam-freeman/

textbookfull.com

Beginning Database Programming Using ASP NET Core 3 With


MVC Razor Pages Web API jQuery Angular SQL Server and
NoSQL 1st Edition Bipin Joshi
https://textbookfull.com/product/beginning-database-programming-using-
asp-net-core-3-with-mvc-razor-pages-web-api-jquery-angular-sql-server-
and-nosql-1st-edition-bipin-joshi/
textbookfull.com

Modern Web Development with ASP NET Core 3 An end to end


guide covering the latest features of Visual Studio 2019
Blazor and Entity Framework 2nd Edition Ricardo Peres
https://textbookfull.com/product/modern-web-development-with-asp-net-
core-3-an-end-to-end-guide-covering-the-latest-features-of-visual-
studio-2019-blazor-and-entity-framework-2nd-edition-ricardo-peres/
textbookfull.com

Pro C# 7 with .NET and .NET Core Andrew Troelsen

https://textbookfull.com/product/pro-c-7-with-net-and-net-core-andrew-
troelsen/

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

ISBN-13 (pbk): 978-1-4842-3374-0 ISBN-13 (electronic): 978-1-4842-3375-7


https://doi.org/10.1007/978-1-4842-3375-7
Library of Congress Control Number: 2018935922

Copyright © 2018 by Derek J. Rouleau


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Jonathan Gennick
Development Editor: Laura Berendson
Coordinating Editor: Jill Balzano
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-
sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member
(owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a
Delaware corporation.
For information on translations, please e-mail [email protected], or visit http://www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book's product page, located at www.apress.com/9781484233740. For more
detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
To my best friend Chris and his father Paul Champagne.
If it wasn’t for you two, I may have never gotten
interested in computer science.
Table of Contents
About the Author����������������������������������������������������������������������������������������������������� ix

About the Technical Reviewer��������������������������������������������������������������������������������� xi


Acknowledgments������������������������������������������������������������������������������������������������� xiii

Introduction�������������������������������������������������������������������������������������������������������������xv

Chapter 1: Getting Started���������������������������������������������������������������������������������������� 1


What Is .NET Core������������������������������������������������������������������������������������������������������������������������� 1
Setting Up Your Application����������������������������������������������������������������������������������������������������������� 2
Creating the Database and Tables (Entities)��������������������������������������������������������������������������������� 3
Creating the Database����������������������������������������������������������������������������������������������������������� 19
Adding Data to a Table���������������������������������������������������������������������������������������������������������������� 21
Retrieving Data from a Database and Displaying It�������������������������������������������������������������������� 31
Deleting Data from a Database��������������������������������������������������������������������������������������������������� 33
Deleting a Single Record������������������������������������������������������������������������������������������������������� 33
Deleting Multiple Records����������������������������������������������������������������������������������������������������� 40
Updating Data in a Table������������������������������������������������������������������������������������������������������������� 42
Summary������������������������������������������������������������������������������������������������������������������������������������ 45

Chapter 2: Working with Multiple Tables���������������������������������������������������������������� 49


Adding Data to a Table That Has Foreign Keys��������������������������������������������������������������������������� 50
Retrieving Data from Multiple Tables������������������������������������������������������������������������������������������ 75
Updating Tables��������������������������������������������������������������������������������������������������������������������������� 81
Updating Multiple Records���������������������������������������������������������������������������������������������������� 91
Summary������������������������������������������������������������������������������������������������������������������������������������ 95

v
Table of Contents

Chapter 3: Stepping Beyond the Basics������������������������������������������������������������������ 97


Specifying Fields������������������������������������������������������������������������������������������������������������������������� 98
Joins����������������������������������������������������������������������������������������������������������������������������������������� 101
Left Outer Join��������������������������������������������������������������������������������������������������������������������� 102
Right Outer Join������������������������������������������������������������������������������������������������������������������� 104
Cross Join���������������������������������������������������������������������������������������������������������������������������� 109
Inner Join: Method Syntax��������������������������������������������������������������������������������������������������� 110
Grouping����������������������������������������������������������������������������������������������������������������������������������� 112
Query Syntax����������������������������������������������������������������������������������������������������������������������� 112
Method Syntax��������������������������������������������������������������������������������������������������������������������� 114
Logical Operators���������������������������������������������������������������������������������������������������������������������� 115
Logical OR��������������������������������������������������������������������������������������������������������������������������� 119
Paging and Filtering Results����������������������������������������������������������������������������������������������������� 121
Concurrency������������������������������������������������������������������������������������������������������������������������������ 125
Summary���������������������������������������������������������������������������������������������������������������������������������� 130

Chapter 4: Data Validation and POCOs������������������������������������������������������������������ 133


Validation Using DataAnnotations��������������������������������������������������������������������������������������������� 134
Using Recursion������������������������������������������������������������������������������������������������������������������ 143
POCOs��������������������������������������������������������������������������������������������������������������������������������������� 153
Helper Classes��������������������������������������������������������������������������������������������������������������������� 156
Validating Using a Class������������������������������������������������������������������������������������������������������ 168
Summary���������������������������������������������������������������������������������������������������������������������������������� 177

Chapter 5: Stored Procedures, Table Design, and Modifications�������������������������� 179


Stored Procedures�������������������������������������������������������������������������������������������������������������������� 179
Calling a Stored Procedure with One Parameter����������������������������������������������������������������� 185
Inserting Into Multiple Tables���������������������������������������������������������������������������������������������� 189
Table and Entity Design������������������������������������������������������������������������������������������������������������� 192
Making Changes to the Table���������������������������������������������������������������������������������������������������� 194
Summary���������������������������������������������������������������������������������������������������������������������������������� 201

vi
Table of Contents

Chapter 6: ASP.NET MVC and EF Core 2.0������������������������������������������������������������� 203


Setting Up the Application�������������������������������������������������������������������������������������������������������� 204
Database-First Development���������������������������������������������������������������������������������������������������� 207
Creating Controllers and Views������������������������������������������������������������������������������������������� 209
Page Navigation������������������������������������������������������������������������������������������������������������������� 214
The Home Page and Adding an Image�������������������������������������������������������������������������������� 216
Error Handling��������������������������������������������������������������������������������������������������������������������� 218
Displaying Events by Location��������������������������������������������������������������������������������������������� 224
Sorting Results�������������������������������������������������������������������������������������������������������������������� 228
ASP.NET MVC Basics����������������������������������������������������������������������������������������������������������������� 230
Strongly Typed Views����������������������������������������������������������������������������������������������������������� 232
Why Use MVC?��������������������������������������������������������������������������������������������������������������������� 234
Summary���������������������������������������������������������������������������������������������������������������������������������� 235

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

Chapter 8: Wrap Up and Where to Go Next����������������������������������������������������������� 289


Not Just C# Anymore���������������������������������������������������������������������������������������������������������������� 289
Cross Platform�������������������������������������������������������������������������������������������������������������������������� 295
Unit Testing������������������������������������������������������������������������������������������������������������������������������� 297
More on LINQ���������������������������������������������������������������������������������������������������������������������������� 312
SQL Server Profiler�������������������������������������������������������������������������������������������������������������� 315

vii
Table of Contents

Change Tracking����������������������������������������������������������������������������������������������������������������������� 316


Summary���������������������������������������������������������������������������������������������������������������������������������� 321

Appendix A: Database Script for Chapter 6���������������������������������������������������������� 323


Database Diagrams������������������������������������������������������������������������������������������������������������������� 329

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
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.

Who This Book Is For


This book is for someone who has never used Entity Framework Core and is looking
for a new way to access databases. Although we focus on SQL Server in this book,
according to Microsoft, it is possible to connect to MySQL, PostgreSQL, and MyCAT as
well. (However, there is no Oracle support for EF Core yet, but hopefully there will be in
the future.) If you have not programmed in any language before, you may have a little
bit of trouble, as we don’t explain the basics of C# or ASP.NET. You may not understand
or might miss some key concepts. If you are coming over from Visual Basic, you will
probably do fine, although you need to remember to add those pesky semicolons at the
end of your code lines.
Although we do use quite a bit of LINQ in this book, it is not required that you have
any background in LINQ prior to running any of the examples. It would be wise to do
some follow-up reading on LINQ after you complete this book, but you should be able to
piece together most of what you need to do after completing these examples. If you get
stuck, an Internet search will give you a better idea of what you are looking at so you can
make a better decision as to what to use.

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.

Notes About NuGet Packages


At the time of the writing of this book, some of the packages that we use were still only
available in preview1-final or preview2-final. If you find that you are getting errors with
your application, it may be due to a mixture of the preview and the release versions. It’s
better to either use all preview or all release versions with your application, as that seems
to be the safest. When you use the preview packages, sometimes you will get warnings
in which it’s trying to find the best match. Normally those warnings won’t cause you any
problems when you run your code and are more of an annoyance than anything.

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.

What Is .NET Core


Let’s take a quick moment to cover something that some of you may be wondering—
what is the difference between .NET and .NET Core? First off, .NET Core is cross
platform, so if you want to run an application on Windows, Linux, or Mac, .NET Core is
your tool. Due to its compact nature, .NET Core also gives better performance. The other
nice thing is that you can always start with .NET Core and, if you find you need more
features, you can switch to the full version of the .NET Framework. This is especially true
if you are writing a service.

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!

Setting Up Your Application


Follow these steps to set up the application:
Step 1: Create a new Visual C# Console App (.NET Core) Application in Visual studio
called ComputerInventory. Again, make sure you are using at least .NET Framework 4.6.1
for your application.
Step 2: Open the NuGet package browser by clicking on Project ➤ Manage NuGet
Packages (see Figure 1-1).

Figure 1-1. Location of NuGet package manager

2
Chapter 1 Getting Started

Step 3: Add the following packages:

• 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.

Figure 1-2. NuGet package manager

That completes the basic setup of your application. Feel free to save your work before
you continue.

Creating the Database and Tables (Entities)


If you have used Entity Framework 6.x or one of the other versions in the past, this
next part will be a little new to you (or perhaps not). We are going to start with a ­code-­
first Entity Framework type of application, as that is somewhat easier when using EF
3
Chapter 1 Getting Started

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).

Figure 1-3. Adding a new folder

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.

Figure 1-4. Creating a new class

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.

Listing 1-1. OperatingSys.cs After You Changed It

using System;
using System.Collections.Generic;

namespace ComputerInventory.Models {
   public partial class OperatingSys {
      public OperatingSys() {
         Machine = new HashSet<Machine>();
      }

      public int OperatingSysId { get; set; }


      public string Name { get; set; }
      public bool StillSupported { get; set; }

      public ICollection<Machine> Machine { get; set; }


   }
}

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
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.

Listing 1-2. MachineType.cs

using System;
using System.Collections.Generic;

namespace ComputerInventory.Models {
   public partial class MachineType {
      public MachineType() {
         Machine = new HashSet<Machine>();
      }

      public int MachineTypeId { get; set; }


      public string Description { get; set; }

      public ICollection<Machine> Machine { get; set; }


   }
}

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.

Listing 1-3. WarrantyProvider.cs


using System;
using System.Collections.Generic;

namespace ComputerInventory.Models {
   public partial class WarrantyProvider {
      public WarrantyProvider() {
         MachineWarranty = new HashSet<MachineWarranty>();
      }

7
Chapter 1 Getting Started

      public int WarrantyProviderId { get; set; }


      public string ProviderName { get; set; }
      public int? SupportExtension { get; set; }
      public string SupportNumber { get; set; }

      public ICollection<MachineWarranty> MachineWarranty { get; set; }


   }
}

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.

Listing 1-4. Machine.cs

using System;
using System.Collections.Generic;

namespace ComputerInventory.Models {
   public partial class Machine {
      public Machine() {
         SupportTicket = new HashSet<SupportTicket>();
      }

8
Chapter 1 Getting Started

      public int MachineId { get; set; }


      public string Name { get; set; }
      public string GeneralRole { get; set; }
      public string InstalledRoles { get; set; }
      public int OperatingSysId { get; set; }
      public int MachineTypeId { get; set; }

      public MachineType MachineType { get; set; }


      public OperatingSys OperatingSys { get; set; }
      public ICollection<SupportTicket> SupportTicket { get; set; }
   }
}

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.

Listing 1-5. MachineWarranty.cs

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; }

      public WarrantyProvider WarrantyProvider { get; set; }


    }
}

Listing 1-6. SupportTicket.cs

using System;
using System.Collections.Generic;

namespace ComputerInventory.Models {
   public partial class SupportTicket {
      public SupportTicket() {
         SupportLog = new HashSet<SupportLog>();
      }

      public int SupportTicketId { get; set; }


      public DateTime DateReported { get; set; }
      public DateTime? DateResolved { get; set; }
      public string IssueDescription { get; set; }
      public string IssueDetail { get; set; }
      public string TicketOpenedBy { get; set; }
      public int MachineId { get; set; }

10
Chapter 1 Getting Started

      public Machine Machine { get; set; }


      public ICollection<SupportLog> SupportLog { get; set; }
   }
}

Listing 1-7. SupportLog.cs

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; }

      public SupportTicket SupportTicket { 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
Chapter 1 Getting Started

Listing 1-8. MachineContext.cs

using System;
using Microsoft.EntityFrameworkCore;
using ComputerInventory.Models;

namespace ComputerInventory.Data {
   class MachineContext : DbContext {
      public virtual DbSet<Machine> Machine { get; set; }
      public virtual DbSet<MachineType> MachineType { get; set; }
      public virtual DbSet<MachineWarranty> MachineWarranty { get; set; }
      public virtual DbSet<OperatingSys> OperatingSys { get; set; }
      public virtual DbSet<SupportLog> SupportLog { get; set; }
      public virtual DbSet<SupportTicket> SupportTicket { get; set; }
      public virtual DbSet<WarrantyProvider> WarrantyProvider { get; set; }

      protected override void OnConfiguring(DbContextOptionsBuilder


optionsBuilder) {
      if (!optionsBuilder.IsConfigured) {

         
optionsBuilder.UseSqlServer(@"Server=ServerName;Database=BegEFCore2;
Trusted_Connection=false;User ID=sa;Password= ");
      }
   }

   protected override void OnModelCreating(ModelBuilder modelBuilder) {


      modelBuilder.Entity<Machine>(entity => {
      entity.Property(e => e.MachineId).HasColumnName("MachineID");

      entity.Property(e => e.GeneralRole)


         .IsRequired()
         .HasMaxLength(25)
         .IsUnicode(false);

      entity.Property(e => e.InstalledRoles)


         .IsRequired()
         .HasMaxLength(50)
         .IsUnicode(false);

12
Chapter 1 Getting Started

      entity.Property(e => e.MachineTypeId).HasColumnName("MachineTypeID");

      entity.Property(e => e.Name)


         .IsRequired()
         .HasMaxLength(25)
         .IsUnicode(false);

      entity.Property(e => e.OperatingSysId).HasColumnName("OperatingSysID");

      entity.HasOne(d => d.MachineType)


         .WithMany(p => p.Machine)
         .HasForeignKey(d => d.MachineTypeId)
         .OnDelete(DeleteBehavior.ClientSetNull)
         .HasConstraintName("FK_MachineType");

      entity.HasOne(d => d.OperatingSys)


         .WithMany(p => p.Machine)
         .HasForeignKey(d => d.OperatingSysId)
         .OnDelete(DeleteBehavior.ClientSetNull)
         .HasConstraintName("FK_OperatingSys");
      });

      modelBuilder.Entity<MachineType>(entity => {
         entity.Property(e => e.MachineTypeId).HasColumnName("MachineTypeID");

         entity.Property(e => e.Description)


            .HasMaxLength(15)
            .IsUnicode(false);
         });

         modelBuilder.Entity<MachineWarranty>(entity => {
            entity.Property(e => e.MachineWarrantyId).HasColumnName
("MachineWarrantyID");

            entity.Property(e => e.MachineId).HasColumnName("MachineID");

            entity.Property(e => e.ServiceTag)


               .IsRequired()

13
Chapter 1 Getting Started

               .HasMaxLength(20)
               .IsUnicode(false);

             entity.Property(e => e.WarrantyExpiration).HasColumnType("date");

             entity.Property(e => e.WarrantyProviderId).HasColumnName


("WarrantyProviderID");

             entity.HasOne(d => d.WarrantyProvider)


                .WithMany(p => p.MachineWarranty)
                .HasForeignKey(d => d.WarrantyProviderId)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("FK_WarrantyProvider");
         });

         modelBuilder.Entity<OperatingSys>(entity => {
            entity.Property(e => e.OperatingSysId).HasColumnName
("OperatingSysID");

            entity.Property(e => e.Name)


               .IsRequired()
               .HasMaxLength(35)
               .IsUnicode(false);
         });

         modelBuilder.Entity<SupportLog>(entity => {
            entity.Property(e => e.SupportLogId).HasColumnName("SupportLogID");

            entity.Property(e => e.SupportLogEntry)


               .IsRequired()
               .IsUnicode(false);

            entity.Property(e => e.SupportLogEntryDate).HasColumnType("date");

                entity.Property(e => e.SupportLogUpdatedBy)


                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);

14
Chapter 1 Getting Started

                entity.Property(e => e.SupportTicketId).HasColumnName


("SupportTicketID");

                entity.HasOne(d => d.SupportTicket)


                   .WithMany(p => p.SupportLog)
                   .HasForeignKey(d => d.SupportTicketId)
                   .OnDelete(DeleteBehavior.ClientSetNull)
                   .HasConstraintName("FK_SupportTicket");
          });

          modelBuilder.Entity<SupportTicket>(entity => {
             entity.Property(e => ­e.SupportTicketId).HasColumnName
("SupportTicketID");

             entity.Property(e => e.DateReported).HasColumnType("date");

             entity.Property(e => e.DateResolved).HasColumnType("date");

             entity.Property(e => e.IssueDescription)


                .IsRequired()
                .HasMaxLength(150)
                .IsUnicode(false);

             entity.Property(e => e.IssueDetail).IsUnicode(false);

                entity.Property(e => e.MachineId).HasColumnName("MachineID");

             entity.Property(e => e.TicketOpenedBy)


                .IsRequired()
                .HasMaxLength(50)
                .IsUnicode(false);

             entity.HasOne(d => d.Machine)


                .WithMany(p => p.SupportTicket)
                .HasForeignKey(d => d.MachineId)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("FK_Machine");
         });

15
Exploring the Variety of Random
Documents with Different Content
him with an emotion of which he at first misinterpreted the cause--
when, by an effort which sent back the blood to her heart, she told
him of her doubts, of her fears, shrinking from meeting the bright
eye which rested so keenly upon her--the first sentiment awakened
in his breast was one of surprise, succeeded by something akin to
indignation. Was he to be called upon to explain his views, to give
an account of his opinions! Were the depths of his mind to be
sounded by the feeble thread of a woman's judgment! What was it
to her what he thought or believed--it was not to be expected that
she should understand him! Why was theology dragged in at all,
where the question was between heart and heart! "Such matters
might suit," as he observed, with a sarcastic smile, "the discussion of
grave doctors at convocation, but could scarcely occupy now the
attention of him whose mind was absorbed by but one object--the
deep, passionate love which he bore towards her in whom all his
hopes of happiness centred!"
Sir Amery had at first suspected Mrs. Vernon of throwing
frivolous difficulties in the way, in order to enhance the value of the
prize which he sought, and to prevent the baronet from feeling that
the merchant's daughter was too easily won. Flora's silent anguish,
however, and her mother's quiet decision, soon undeceived him on
this point. He saw that the danger was real, the opposition which he
encountered, sincere. He then changed his position altogether; and
dropping the calm, almost sarcastic manner in which he had at first
replied to Mrs. Vernon, he burst into a strain of fervid, glowing
eloquence, pouring forth those impassioned words which excite the
feelings and confound the judgment. He pleaded his own cause as
those only can plead whose more than life is at stake.
To Flora, such words were irresistible. If doubts or scruples had
been raised in her mind, they were swept in a moment away, as the
rushing cataract, dashing from a height, whirls along the autumn
leaves that have dropped on its surface! But as easily could that
roaring cataract break the arch of the rainbow that glistens at its
foot, as the torrent of eloquence to which she listened warp the
settled judgment of the parent. She needed not to be persuaded
that Sir Amery loved--she believed Flora to be worthy of the
warmest affection which ever glowed in the heart of man; but no
sentence which he uttered altered her conviction that he was one
who, however gifted with earthly wisdom, was yet a stranger to the
knowledge which alone can make man wise unto salvation.
Sir Amery read in the expression of her sad eye that, as far as
regarded Mrs. Vernon, all that he had spoken had been uttered in
vain. Repressing the fierce resentment which swelled in his breast,
he addressed himself more exclusively to Flora, whose tears were
her only reply. Mrs. Vernon saw that the love of her only child for
one whom, some few weeks before, she had met as a stranger, was
overcoming even that affection which had grown with her growth
and strengthened with her strength; she felt herself the only barrier
between her daughter and a danger to which Flora was blind, and
she dreaded lest that barrier might be passed. Her nerves
overstrained, her feelings wounded, her fears for the moment
overmastering her faith, Mrs. Vernon sank back on her chair, the
paleness of death overspread her face, a feint sigh burst from her
whitening lips!
The sight of her mother in this state roused all that deep
affection which Flora had ever borne towards her parent. In a
moment she was at her side, supporting her drooping head,
covering the pallid brow with her tears.
"Oh, mother, mother!" she sobbed forth, "look not thus. I will do
anything--everything that you will! Leave me, leave me, Sir Amery!"
she continued, in tones of passionate grief; "I never can--I never
will--marry without the consent of my mother!"
"You do not bid me despair?" exclaimed Sir Amery, grasping the
unresisting hand which trembled in his. "Flora, you do not bid me
despair?"
"Go--go. Perhaps a time may come--perhaps--only leave me--for
pity's sake, leave me!"
"You shall be obeyed," replied Sir Amery, pressing her hand
fervently to his lips; "Flora, my heart's life, you shall be obeyed. But
notwithstanding all the obstacles which narrow-minded bigotry
would raise up between us, did all the powers of earth combine to
separate those whose hearts are united, love like mine should
trample down those obstacles, and, in defiance of the opposition of
the world, you should be mine: yes, Flora, idol of my soul! you shall
be mine!"
He was gone!--gone with burning words on his lips, passionate,
indignant emotions in his heart: he was gone, and left desolation
behind him!

CHAPTER XIII.
THE MOTHER'S TRIAL.
"Sweet are the uses of adversity," writes the great poet of Nature.
Experience confirms the blessed truth proclaimed by Revelation, that
"they who sow in tears shall reap in joy." The lips that meekly kiss
the rod find that, like Aaron's, it will blossom, and bear the fruits of
peace, and even joy. Sorrow has so often been the step to
sanctification, that we can scarcely wonder that the means have
sometimes been mistaken for the end--that it has been thought that
grief has in itself some purifying power, until much suffering on earth
is almost regarded as a passport to heaven!
And yet how mistaken is this view!--how contrary to the
warning in the Scriptures, that there is a sorrow of the world that
worketh death? If some tears are like the dew that descends on the
earth, shedding fertility and beauty on all sides, others are like the
waters of the Dead Sea, bitter and unblessed: buried joys lie
beneath, and a desert spreads around!
Such were the tears of Flora, on this blighting of her fondest
hopes--this separation from him whom she regarded as the lode-star
of her existence. Earth to her held nothing more to live for. All was a
weary blank like that before the darkened eyes of the blind. She no
longer found pleasure in aught that had pleased her before: her
flowers drooped neglected, her instrument was dumb, her books
were unopened, her pencil untouched. And as with her pleasures, so
with her duties--all were alike disregarded. The poor listened in vain
for her well-known step; her pupils wondered at her absence from
the school; Emma openly complained of unkindness and neglect;
while her children were shunned by Flora, or their presence endured
with scarce concealed dislike and irritation. She noticed not, cared
not, for the improvement wrought in them by Mrs. Vernon's patient
care; she only felt that their noisy merriment jarred on her wounded
spirit; she was almost angry to think that they were happy! Flora
was a changed being--changed even to her mother. The parent's
fond glance never met an answering smile; her tender words
received short, sullen answers. Flora saved no pang to the gentle
breast which maternal love gave her such power to wound. Not that
she uttered a murmur--pride would not have suffered that; but there
was reproach in the downcast, tearful eye--reproach in the tone of
the mournful voice, in the languid step, the drooping form. By
neglect of her own health, by sullen yielding to despair, Flora was
revenging herself upon her mother.
And what was the state of her heart towards her heavenly
Father? Alas! could the thoughts and feelings of the unhappy Flora
have been written down, she would have started and trembled to
see how near the breathings of a repining, gloomy spirit approached
to blasphemy! She deemed herself hardly, unmercifully dealt with.
She marvelled why she had been raised for a moment to the very
pinnacle of human felicity, to be dashed down into the deep gulf of
despair! Was the Almighty indeed a pitying Father? Had He led her
into the paths of peace? Had He not rather filled her cup with
bitterness, and withered her soul with disappointment? Nay, was it
not religion that lay at the root of all her misery? Were not the
conscientious misgivings of her mother as the worm that had
destroyed the gourd that she delighted in? Had Mrs. Vernon's views
been less strict and puritanical--less bigoted, as Flora called them, in
the anguish of her soul--would not her daughter have been the
happiest of women?--would not she herself have been the proudest
of mothers?
Such thoughts were sinful, marked with the deepest stain of
ingratitude; yet Flora indulged in them freely. She almost accused
Providence in secret of having exposed her to trials beyond what she
could bear; unmindful of the fact that she had herself, in impatience
of petty annoyances, chosen the path which, however flowery at
first, she had found to be strewn with sharp thorns. If she was
conscious that her faith was growing weak, and her love towards
God becoming cold, she laid the blame upon the cruel circumstances
of the position in which the Almighty had placed her. She had loved
and served the Lord--at least so she deemed--when she was happy;
but when His hand lay so heavy upon her, she was ready to forget
all past mercies, all present blessings, all bright hopes of a blissful
future. With Jonah her spirit exclaimed, "I do well to be angry:" with
Elijah, "It is enough; take away my life!" Impatient to throw down
the burden which her unchastened will refused to sustain, she
longed, almost prayed, for death--little deeming in her present state
how unfit she was to die. The sun of trial was now indeed glowing
with intense and burning heat on the seed which had been sown in
rocky ground; the plant which had shown in the world's eye so fair,
unwatered by grace, having no root in itself, in the time of
temptation withered away.
Deep was the affliction of Mrs. Vernon; darker and darker grew
the path before her. She had stood firm against the sophistry of
human wisdom, the power of human eloquence; she had resisted
even Flora's pleading tears: but to see, week after week, and month
after month, her child wasting to a shadow before her, was a
lengthened torture to her loving heart which wore away the very
thread of her life. In vain medical advice was sought for Flora. There
was no physician to "minister to a mind diseased;" all the skill of
man was unavailing where the patient chose death rather than life.
There was an awful possibility before Mrs. Vernon, too terrible to
contemplate, but which recurred to her mind again and again, as
she gazed on the fading form of her child. There was nothing which
appeared to rouse Flora, or to excite in her a moment's interest,
except the letters which she received from Ada, and which were
perused only by herself. Mrs. Vernon never sought to know their
contents; she felt that her daughter's confidence and affection were
now given to another, and that she herself stood in the position of a
tyrant towards one who was far dearer to her than life!
"Have I indeed done what was right? or have I mistaken my
duty--sacrificed to blind prejudice the happiness of my child--
destroyed her health, her peace--ruined her hopes, in my ignorant,
misguided zeal?" Such were the bitter reflections which recurred
again and again, and ever with increasing bitterness, to the mind of
the unhappy mother. In vain her pastor endeavoured to support her
with the consolations of religion--to assure her that she had not only
acted faithfully, but wisely: she could not endure to see the
consequences of her own decision, still less to contemplate what
might possibly be its final result.
Autumn rain was fast descending, streaming from the heavy
black clouds, while ever and anon a wild gust of wind stripped the
boughs of their faded leaves, and scattered them far and wide.
Emma tried to beguile the weary time with a novel, but looked up
from it every five minutes with a languid sigh, to complain of "the
horrid weather," and contrast the English climate with that of her
native island. The children were restless and noisy, impatient of the
confinement of the house, till Mrs. Vernon found employment for
them all in looking over the curiosities of an old cabinet.
Where was Flora? Her mother sought her in the small sitting-
room in which her daughter usually pursued her occupations. Her
books, her piano, her desk, were there. The room was not, however,
now occupied; Flora was in her own apartment. Mrs. Vernon noticed
that an album was laid on the desk, in which Flora usually wrote her
poetical effusions; and the sight of it made the mother hope that at
least one favourite occupation had not been relinquished by her
daughter. Often had Mrs. Vernon copied out verses from that album,
and shed tears of pleasure over them. She opened the book to see if
Flora had recently added to their number. Between the last written
pages there were compressed flowers, their beauty faded, their life
gone; yet precious, perhaps, as relics of the hours when they had
bloomed as freshly as the hopes which, like them, had withered. The
last verses in the volume were new to Mrs. Vernon; they bore the
date but of yesterday; and she with anguish perused them as the
transcript of the feelings of a young being whose life had not yet
numbered twenty years.

LINES.

Is it sinful to gaze on the morning sun,


And wish that the gates of the west he had won--
That life's day were over, its labours done?

Is it sinful to mark the first silver hair


'Mid dark tresses touched by the hand of care,
And wish time had shed all his winter there?

Is it sinful in life no joy to take,--


To feel like a captive bound to the stake
By a chain that galls us, and will not break?

Some fear to die: 'tis not so with me;


Rather, O Death, I pine for thee!
I long in the quiet grave to be!

"Oh! this is too much--too much!" exclaimed Mrs. Vernon, wringing


her hands. "I can endure anything myself, but I cannot--oh, I cannot
break the heart of my child!"
She hastened to Flora's apartment with a quick and agitated
step. She unclosed the door--she saw Flora on her knees, her hair
dishevelled, her bosom heaving with sobs, as she pressed again and
again convulsively to her lips a little diamond locket which she held
in her hand.
Flora started to her feet at the sound of her mother's entrance:
as she did so a letter fell to the ground. Mrs. Vernon's eye rested
upon it for a moment: the handwriting was not that of Ada.
"Oh! mother--mother--forgive me; it was--from him!"
"He loves you still?"
"More than ever!" exclaimed Flora, bursting into a fresh flood of
tears.
"Then let him be happy with you!" cried the mother, folding her
child in her arms, and kissing away her tears, while her own flowed
freely and fast. "I can resist no longer. Oh, God forgive me if I do
wrong! Flora, my own beloved! be united to the husband of your
choice; you have your mother's consent and her blessing!"
On the scenes that followed I will not dwell, but leave them to
the imagination of the reader. On the day when the first snow fell,
Flora was the bride of Sir Amery.

CHAPTER XIV.
THE VISIT.

More than two years had now elapsed since the day when, in the
little church of Wingsdale, Flora had plighted her troth to him whom
she so deeply loved, while many a fervent prayer arose for her
happiness from the poor whom she had tended, the young whom
she had taught. The interval between her engagement and her
marriage had been one of brightness to Flora. A mountain's weight
seemed to have been removed from her spirits, and with the
elasticity which youth and hope give, they had more than rebounded
to their former elevation. Again she had smiles and kind words for
all, and she appeared resolved by her winning sweetness of manner
to deepen the regrets of the village at losing its "sunshine." Mrs.
Vernon had stifled her own misgivings, that she might cast no
shadow on the bliss of the young bride; and no one could have told
from her outward manner how heavy lay the heart within. Even
Emma had shaken off a little of her languor, roused to something
like interest by the excitement of a wedding. Her children had
brought their little offerings, prepared in mysterious secrecy with the
assistance of their grandmother, who was to them teacher,
companion, and confidant; and Flora's surprise and thanks on
receiving their presents almost realized their juvenile expectations.
More than two years had rolled their course since that exciting,
joyous day, when a cab drove up to the door of a large house in
Cavendish Square, and a lady stepped out and rang the bell. She
was attired in habiliments which once had been handsome, but
which had decidedly seen their best days; the rich silk dress had
been dyed, the shawl was faded, the sable boa showed tokens of
age, and neat fingers had repaired the Lisle lace veil which gave
grace to the bonnet of straw. In the staid manner and somewhat
care-worn face, where certain lines were traced across the brow
which was smooth some two years ago, we mark a change beyond
that which time would have made in our old acquaintance Ada.
"Ada! oh, how delighted I am to see you! What an age it is
since we met!" cried Flora, as the visitor was ushered into the
elegant apartment of Lady Legrange, and the cousins exchanged an
affectionate embrace.
Has Flora also been altered by the plain gold ring, which often
works wonders as strange as those wrought by an enchanter?
Flora is lovely as ever, her beauty enhanced by a womanly
dignity which beseems the baronet's wife. But she too has lost the
joyous brightness which rested on her gentle countenance when Ada
first visited Wingsdale. An expression of thought, almost of
melancholy, is there; and she certainly looked far happier in her
gipsy bonnet, seated on the gnarled roots of the old oak, than she
does now in her spacious mansion, robed in velvet and surrounded
by luxury.
"I could not resist the temptation of coming to see you!" cried
Ada, sitting with Flora's hand clasped in her own, and surveying her
with a look of affectionate interest.
"I hope that you have brought your twins to London with you?"
said Flora.
"Oh, the little cherubs! how I should delight to show them to
you! But we left them in Wiltshire; it is a serious matter to travel
with two infants not a year old."
"Then I am afraid that your stay in London will be but short,"
observed Lady Legrange, "with two such powerful magnets drawing
you away."
"Only two!" laughed Ada; "you forget my husband's children,--a
whole scale of magnets, from five feet five to three feet nothing! I
thought that I should never have managed to get away at all! But
the Major was obliged to come to town to fit out his middy, and I
took such a longing to revisit my old haunts, look at old faces, hear
the sounds of carriage wheels, and knocks at the door, and street
cries, and hurdy-gurdies again, that, like a dutiful mamma, I must
see Jack off myself, and pay a flying visit to dear smoky London."
"I can scarcely fancy you the staid, sober mother of such a large
family!" exclaimed Flora.
"Very odd--isn't it? reversing the order of nature; instead of the
quiet spinning caterpillar turning into the gay butterfly, the butterfly
doffing its silken wings and beginning to crawl through the routine of
daily duties, a prisoner to its cabbage-leaf. Only imagine me, Flora,
mending stockings, shaping out pinafores, bandaging cut fingers and
broken heads, scolding tradespeople, keeping servants in order,
paying bills, and dancing babies till my arms ache!"
"I should think the last a very delightful occupation," said Flora,
suppressing a sigh.
"None but a mother can tell how delightful," replied Ada; "but I
do not take so kindly to all my domestic employments. I never yet
took pleasure in solving the problem how far a shilling would go, nor
finding out how it is that boys are always wanting new shoes, and
how elbows and knees are perpetually running a race as to which
should first run through the clothes. I believe that children have
found out the secret of perpetual motion, to the great discomfort of
those who have to look after little rogues!"
"But children make a house so cheerful," said Flora,
abstractedly.
"And now, my dear child--ah! you see that I can't get over my
old way of talking to you yet--do give me your last news from
Wingsdale. You know that I'm such a shocking correspondent that I
know as little of what passes in the world beyond Salisbury Plain as
if I were a denizen of the moon."
"Poor old Mrs. Ward, my mother tells me, is now a confirmed
invalid, and unable to leave her bed."
"And your sweet mother herself?"
"She never mentions her own health; her letters are full of the
children."
"Ah! the whity-brown legion of little horrors, who like a swarm
of hornets literally drove you out of Laurel Bank, and compelled you
to take refuge in Grosvenor Square! I suppose that they have been
undergoing the process of taming, at which my aunt is so famous,
and that Johnny now does not scratch out any one's eyes, and that
Lyddie may be trusted in a store-room full of treacle and sugar. I
should think your mother a first-rate hand at bringing up children,
judging from the charming specimen before me!"
Flora neither smiled nor blushed at the flattery now.
"But tell me how they all appeared when you were last at Laurel
Bank."
Then, indeed, the colour rose to Flora's pale cheek, and it was
with an appearance of some embarrassment that she replied, "I
have not been there since you were there, on the day of my
marriage."
Ada suppressed the exclamation of astonishment that was upon
her tongue, for she saw that its utterance would give pain.
"My dear husband has been so much engaged--of course I
could not leave him--it is so difficult sometimes to make
arrangements--but I hope soon--" Flora stopped short, for her lips
were not accustomed to utter an absolute untruth.
"How your mother must be longing to see you! I should not
have thought that she could have lived so long without you!"
"Words cannot express how I long to see her!" exclaimed Flora,
with tears in her eyes.
"I think that it might be managed in some way. If you could not
visit Wingsdale, she might come to London--"
Flora looked so uneasy at the proposition that Ada changed the
conversation in pure good nature, wondering much in her mind what
could have occurred to separate a parent so much beloved from so
dutiful a daughter.
"I hope that you have not given up your pen, Flora; that you
don't think that your talented husband the author does enough in
that line for you both?"
"Oh, I write a little sometimes," said Flora, in a tone of
indifference.
"I never read anything so pretty as your hymns. Do you know,
Flora," Ada added more gravely, "that I have often thought over the
verses which you wrote during my first visit to Wingsdale, after we
heard that solemn sermon from Mr. Ward on the subject of the
sower and his seed!"
"I had almost forgotten them," said Flora.
"And the sermon too?"
"Well--I have heard so many since."
"Ah! that is the thing, you have lived in such an atmosphere of
piety."
"Oh, don't speak so!" cried Flora hurriedly.
"It does seem to me," observed Ada, folding her hands, "that it
is a great deal more difficult for some people than for others to lead
a religious life. Look how differently you were brought up from what
I was; is there any wonder that we are so different now? I had been
taught to think of nothing but gaiety, and shining in the world, and
making a sensation, and all that sort of thing; I lived in a perpetual
round of amusements: so pleasure was my danger then, and I
fancied that when the time for pleasure was past, my difficulties
would vanish, and that I should grow serious as I grew old. Well, I
follow your example, and marry, and am taken completely from the
world; but I am plunged into a little bustling world of my own, and I
have so much to think of, so much to do, that I have really no time
for religion. Instead of the pleasures, come the cares of this life."
"Cast your cares upon Him, for He careth for you," faintly
murmured Lady Legrange.
"Ah, Flora, you were never like any one else; I always feel
better when I am near you." Flora's brow contracted a little, as if she
were in pain, and she turned her head away from the speaker.
"I wish that I could always have you beside me," continued
Ada; "it would be such a comfort to have your wise, calm advice!"
"It is so much easier to give advice than to take it home to
ourselves," said Flora, with something like a sigh.
The ladies then conversed for some time together on topics of
general interest. Flora really enjoyed seeing her old companion, and
would gladly have invited both Ada and her husband to her house,
to remain there during their stay in London; but she did not venture
even to ask them to dinner. Sir Amery, she knew, would have had no
objection to the society of the lively Ada; but the Major, a simple,
blunt man, with more kindness in his heart than polish in his
manners, did not suit the refined taste of the baronet, and must "be
kept at a proper distance." All that Flora could do was by the
cordiality of her own manner to endeavour to smooth away from the
mind of her cousin any sense of unkindness, or even of ingratitude,
which might arise from no invitation being given; and Ada left the
house satisfied that Flora was not changed, though with a rising
doubt as to whether she were happy.

CHAPTER XV.
THE WIFE.

And was Flora happy in her new life? She had much to render her
so, according to the opinion of the world. She had made what would
be called a brilliant marriage; she was united to one who loved her,
and whom she passionately loved; she was surrounded by all that
could please the eye or charm the taste; she had leisure for every
graceful occupation; she was not weighed down by a multiplicity of
home-cares; she had a life of ease, it might be deemed of
enjoyment: and yet, with all this, Flora was not happy. The sunshine
of her existence seemed to have passed away.
Let us examine more closely into the causes of the melancholy
which often rested like a cloud on her soul.
In the first place, Flora was childless; and this, to a loving spirit
like hers, was no light trial. She would have given all the grandeur of
her home, all the jewels which glittered in her hair, all the beautiful
things which met her eye wherever she turned it, to feel little arms
clasping her neck, to hear infant lips lisp the sweet name of mother!
Flora had never yet, amidst all the outward forms of religion,
acquired that which is the very essence of it, submission to the will
of the Almighty. Her own will had never been brought into the quiet
subjection which is the result of confidence in God's wisdom and
love, and which is the source of true peace and joy. Like the
Israelites in the wilderness, she "murmured," not with her lips, but in
the depths of her heart.
And Flora pined for her mother; she longed again to rest her
weary head on a parent's bosom, and to be blessed with a parent's
counsels. She could not conceal from herself that her marriage had
separated her from the home of her childhood. It was not so much,
perhaps, that Sir Amery could never quite forgive Mrs. Vernon's
opposition to his marriage, as that he feared her influence over his
wife. Flora had, he thought, too many narrow prejudices, acquired in
her puritanical home: he had no wish to see them strengthened. He
had no wish to have a praying, sermonizing wife who would see sin
in what he thought harmless, and who would always be attempting
to convert him to her own peculiar views of religion. He had put
down, sometimes with a jest, sometimes even with a frown, the few
feeble attempts made by Flora soon after their marriage to win him
to pay more attention to the outward observances of religion. The
Lord did not bless these attempts--they resulted in failure and
disappointment; and Flora bitterly recalled her mother's words, that
it is as impossible for one human being to change the heart of
another, as it would be to bring water from the stony rock, or to call
up fire from the ocean.
Flora's deep love for her husband, even though returned, was
no source of unmingled happiness. She could not rest in calm
confidence upon the hope that all was well with him whom she
deemed the most gifted and the most attractive of men. Blinded as
she was by her admiring affection, Flora had yet many a secret
misgiving and pang, when she heard words pass the lips of her
husband which confirmed the opinion of her mother. She was ever
struggling to persuade herself that the path which he pursued could
not be far wrong; that it was her education which had narrowed her
own mind; that he whose intellect soared to such a height must see
more clearly and widely than others. But it is difficult to overthrow at
once the fabric of opinion which has gradually been forming from
infancy; most difficult when that fabric is founded on truth, and has
the strong though secret support of conscience!
And there was one source of pain which Flora never owned to
others, never even acknowledged to her own heart. She prized the
affection of her husband beyond all earthly--alas! above all heavenly
things; it was her pride, her delight, her treasure: but how could she
trust to links which God had not rivetted? was not her treasure one
which might take wings to itself and flee away? Who could insure
that the love which beauty had awakened would not be perishable
as that beauty? It had not that firmness which arises from steady
principle, that element of immortality which religion alone can give.
Flora was painfully aware that many, and amongst them members of
Sir Amery's own family, had deemed his marriage far below the
expectations which such a man might have formed. Was it quite
impossible that the same thought might sometimes cross the mind
of her husband! There was no sweet babe, no dear pledge of mutual
affection, to bind the baronet's heart to the mother of his child.
Flora's strength was not sufficient to enable her to share all the
amusements of her husband, nor had she enough of mental vigour
to enter into all his pursuits. He shone as a star in many places
where his gentle wife was never seen. Many a lonely evening she
passed, while at some festive board a brilliant circle was listening
delighted to his ever-flowing fountain of wit. Might Sir Amery not
sometimes find her society dull, her conversation insipid, after that
to which he had been accustomed? would her love suffice to make
him happy? could he be contented alone with her? Flora knew that
the baronet had not married her "in the Lord," that his affection for
her was not from the Lord; her whole felicity rested upon an earthly
support--it might be shaken--it might bend--it might give way!
Even when accompanying her husband to scenes of festivity,
neither his loved presence nor the pleasures around her always
chased from the mind of Lady Legrange this phantom of undefined
fear. But that which above all things oppressed the young wife with
a sorrow for which the world has no remedy, was her consciousness
of alienation from her God. What matter how fair be the surrounding
landscape, if the heaven above be of dull leaden hue, if the sun be
blotted from the sky? As regarded the most important of all subjects,
the heart of Flora was cold and hard; and she knew it. No one can
for long worship an earthly idol without feeling the withering effect.
Sir Amery stood between his wife and her God. Flora was careful as
ever to observe the forms of religion, when she could do so without
displeasing her husband; her seat was not vacant in the pew, nor
her name absent from the charity list: but her piety was like a
petrified leaf--it could deceive even her own heart no longer. All that
remained of her religion seemed a vague sense of fear, the fear of a
slave for an offended master, who has the power, perhaps the will,
to chastise. Sometimes Flora doubted whether she had ever been a
Christian at all--whether from childhood she had not played a
hypocrite's part, and whether she were not playing it still. She no
longer thought of heaven as a blissful home, and even when
bitterness of soul made her weary of life, she felt a shrinking from
the thought of death.
And can we wonder that Flora was not happy--that pleasures
failed to amuse her, even conjugal affection to bless? Had she rested
with cheerful content, in that state of coldness, alienation, and
wandering from God, it had been a sign, indeed, that religion had
utterly perished in her soul--that her mother's prayers, and teaching,
and example, had all been in vain.

CHAPTER XVI.
RISING CLOUDS.

"Flora, my love, has anything occurred to distress you?" said the


baronet, as he entered the breakfast room one morning in his
embroidered dressing-gown and slippers, with the newspaper in his
hand.
"Flora, my love, has anything occurred to distress
you?" said the baronet.
Flora looked anxious and unhappy, her eye rested upon an open
letter which she had received by the early post.
"I have heard from Mr. Ward, dearest," she replied; "he gives
me tidings which have made me very uneasy. Scarlet fever, of a
malignant kind, has been raging lately in Wingsdale, and I grieve to
say that two of my brother's children are ill with it now, and it is
feared that the baby is sickening."
The baronet coughed slightly, stirred the fire, and sat down to
sip his chocolate.
"My poor mother!" faltered Flora; "Mr. Ward writes that she is
far from strong; the nursing will be so heavy upon her."
"Have not the children a mother?" said Sir Amery, abruptly.
"Emma has taken such alarm at the idea of infection, that she
has actually hurried away, and engaged a room at a hotel in a town
about ten miles distant from Wingsdale!"
The baronet elevated his handsome brows with an expression of
contempt.
"I fear," continued Flora, with emotion, "that the anxiety and
fatigue will quite break down the health of my mother. She will
watch the children day and night, as she watched me in my fever."
The voice of the daughter trembled as she added, "Oh, Amery! she
needs me to help her; dearest, will you not spare me to her now?
"You!" exclaimed her husband in a loud tone of surprise,
pushing back his chair from the table; "what could have put such an
insane thought into your mind? Do you think that I would suffer you
to go into the midst of infection--to take the place of an unfeeling
woman--to act as nurse to a set of mulattoes--to risk your precious
life for those whom their own mother has deserted?"
"My mother will never desert them," said Flora; "it is to assist
her--"
"We will send a nurse down from London to assist her; let that
set your mind at rest," replied Sir Amery. Then he added, as his
stern features relaxed into a smile, "It is easier to find an efficient
substitute for you, Flora, in the sick-room at Laurel Bank, than at
Lady Montague's soirée to-night."
"The ball!--oh!" exclaimed Flora, leaning back on her chair, "I
have not the heart to go to it!"
"No heart is required," said the baronet, laughing; "we do not
look for such commodities at balls."
Flora was ever submissive and obedient to her husband. She
saw that it was his will that she should accompany him to the party,
and she went, though with a joyless spirit. Decked out in jewels and
costly array, and leaning on the arm of him who attracted every eye,
the fair young wife might have appeared an object of envy to the
proudest dame in the glittering throng. But there was a fount of
sadness in her bosom, which mingled with and imbittered every
pleasure. The music had to her a mournful tone; the gay dancers
flitted before her like images in a dream; she felt it hard to wear a
smile on the lips when the heart was depressed with care. Flora was
glad to choose a quiet corner for herself, where it would be
unnecessary to enter into conversation, where she might remain
unnoticed and unknown.
She was seated beside some ladies who were strangers to her,
and Sir Amery conversing with friends of his own in another
apartment, Flora felt herself alone in a crowd, solitary in the midst of
society. Her thoughts wandered back to her mother's home--she was
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like