Pro Entity Framework Core 2 for ASP.NET Core MVC

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

Model, map, and access data effectively with Entity Framework Core 2, the latest evolution of Microsoft’s object-relational mapping framework. You will access data utilizing .NET objects via the most common data access layer used in ASP.NET Core MVC 2 projects. Best-selling author Adam Freeman explains how to get the most from Entity Framework Core 2 in MVC projects. He begins by describing the different ways that Entity Framework Core 2 can model data and the different types of databases that can be used. He then shows you how to use Entity Framework Core 2 in your own MVC projects, starting from the nuts and bolts and building up to the most advanced and sophisticated features, going in-depth to give you the knowledge you need. Chapters include common problems and how to avoid them. What You’ll Learn Gain a solid architectural understanding of Entity Framework Core 2 Create databases using your MVC data model Create MVC models using an existing database Access data in an MVC application using Entity Framework Core 2 Use Entity Framework in RESTful Web Services Who This Book Is For ASP.NET Core MVC 2 developers who want to use Entity Framework Core 2 as the data access layer in their projects

Author(s): Adam Freeman
Publisher: Apress
Year: 2018

Language: English
City: London
Tags: C#, NET

Contents
About the Author
About the Technical Reviewer
Part I: Introducing Entity Framework Core 2
Chapter 1: Entity Framework Core in Context
Understanding Entity Framework Core
About This Book
What Do You Need to Know?
What Software Do You Need?
What If You Don’t Want to Use Windows?
What Is the Structure of This Book?
Part 1: Introducing Entity Framework Core 2
Part 2: Entity Framework Core 2 in Detail
Part 3: Advanced Entity Framework Core 2
Where Can You Get the Example Code?
Where Can You Get Corrections for This Book?
How Can You Contact Me?
Summary
Chapter 2: Your First Entity Framework Core Application
Getting Ready
Installing .NET Core
Installing Visual Studio 2017
Adding the Visual Studio Extensions
Creating the Project
Setting the Scene
Creating the Project
Adding the Bootstrap CSS Framework
Configuring the HTTP Port
Creating the Data Model and Context Classes
Creating the Controller and Views
Configuring Entity Framework Core
Configuring the Connection String
Configuring the Startup Class
Preparing the Database
Testing the Application
Summary
Chapter 3: Working with Databases
Preparing for This Chapter
Exploring the Database
Examining the Database Tables
Examining the Database Content
Understanding SQL
Querying Data
Manually Querying the Database
Filtering Data
Selecting and Ordering Columns
Ordering Rows
Examining the Entity Framework Core Query
Understanding Query Parameters
Storing and Updating Data
Updating Existing Data
Deleting Data
Joining Data
Preparing the Database
Performing a Join
Summary
Chapter 4: SportsStore: A Real (Data) Application
Creating the Project
Configuring the MVC Framework
Adding the Model
Adding a Repository
Adding a Controller and View
Adding the Finishing Touches
Running the Example Application
Summary
Chapter 5: SportsStore: Storing Data
Preparing for this Chapter
Configuring Entity Framework Core
Configuring Entity Framework Core Logging Messages
Preparing the Data Model
Defining a Primary Key Property
Creating the Database Context Class
Updating the Repository Implementation
Preparing the Database
Configuring the Connection String
Configuring the Database Provider and Context Class
Creating the Database
Running the Application
Avoiding the Query Pitfalls
Understanding the IEnumerable Pitfall
Understanding the Duplicate Query Pitfall
Avoiding a Query Using CSS
Forcing Query Execution in the Repository
Common Problems and Solutions
Problems Creating or Accessing the Database
The “No executable found matching command dotnet-ef” Error
The “Build Failed” Error
The “The entity type requires a primary key to be defined” Error
The “There is already an object named in the database” Exception
The “A Network-Related or Instance-Specific Error Occurred” Exception
The “Cannot Open Database Requested By The Login” Exception
Problems Querying Data
The “Property Could Not Be Mapped” Exception
The “Invalid Object Name” Exception
The “There is Already an Open DataReader” Exception
The “Cannot Consume Scoped Service from Singleton” Exception
The Stale Context Data Problem
Problems Storing Data
Objects Are Not Stored
Only Some Property Values Are Not Stored
The “Cannot Insert Explicit Value for Identity Column” Exception
Summary
Chapter 6: SportsStore: Modifying and Deleting Data
Preparing for This Chapter
Modifying Objects
Updating the Repository
Updating the Controller and Creating a View
Updating Only Changed Properties
Performing Bulk Updates
Updating the Views and Controller
Updating the Repository
Using Change Detection for Bulk Updates
Deleting Data
Common Problems and Solutions
Objects Are Not Updated or Deleted
The “Reference Not Set to an Instance of an Object” Exception
The “Instance of Entity Type Cannot be Tracked” Exception
The “Property Has a Temporary Value” Exception
Updates Result in Zero Values
Summary
Chapter 7: SportsStore: Expanding the Model
Preparing for This Chapter
Creating a Data Model Relationship
Adding a Data Model Class
Creating the Relationship
Updating the Context and Creating the Repository
Creating and Applying a Migration
Creating a Controller and View
Populating the Database with Categories
Using a Data Relationship
Working with Related Data
Selecting a Category for a Product
Creating and Editing Products with Categories
Adding Support for Orders
Creating the Data Model Classes
Creating the Repository and Preparing the Database
Creating Controllers and Views
Storing Order Data
Common Problems and Solutions
The “ALTER TABLE conflicted with the FOREIGN KEY” Exception
The “UPDATE Conflicted with the FOREIGN KEY” Exception
The “The Property Expression ‘x => x.’ is Not Valid” Exception
The “Type of Navigation Property Does Not Implement ICollection” Exception
The “The Property is Not a Navigation Property of Entity Type ” Exception
The “Invalid Object Name ” Exception
Objects Are Deleted Instead of Being Updated
The Class Name for Related Data Is Displayed in a View
Summary
Chapter 8: SportsStore: Scaling Up
Preparing for This Chapter
Creating a Seed Data Controller and View
Scaling Up Data Presentation
Adding Support for Pagination
Creating the Paginated Collection Class
Updating the Repository
Updating the Controller and View
Adding Search and Ordering Support
Applying the Data Presentation Features to Categories
Indexing the Database
Creating and Applying Indexes
Common Problems and Solutions
Queries for Pages Are Too Slow
Applying the Index Migration Times Out
Creating an Index Does Not Improve Performance
Summary
Chapter 9: SportsStore: Customer Features
Preparing for This Chapter
Removing the Timing Statements
Adding a View Import
Modifying the Data Model
Adding Product Seed Data
Preparing the Database
Displaying Products to the Customer
Preparing the Data Model
Creating the Store Controller, Views, and Layout
Creating the Return URL
Testing the Store Display
Adding the Shopping Cart
Enabling Persistent Session Data
Configuring Sessions in the Application
Creating the Cart Model Class
Creating the Controller and Views
Creating the Views
Testing the Ordering Process
Common Problems and Solutions
Clicking a Page Button Manages the Wrong Data Type
Clicking a Page Button Has No Effect
The “Cannot Insert Explicit Value for Identity Column” Exception
Session Objects Are Null
Session Objects Are Lost or Inconsistently Available
Summary
Chapter 10: SportsStore: Creating a RESTful Web Service
Preparing for This Chapter
Creating a Web Service
Creating the Repository
Creating the API Controller
Testing the Web Service
Projecting a Result to Exclude Null Navigation Properties
Including Related Data in a Web Service Response
Avoiding Circular References in Related Data
Querying for Multiple Objects
Completing the Web Service
Updating the Controller
Common Problems and Solutions
Null Property Values When Storing or Updating Objects
Slow Web Service Requests
The “Cannot Insert Explicit Value for Identity Column” Exception
Summary
Part II: Entity Framework Core 2 in Detail
Chapter 11: Working with Entity Framework Core
Creating the ASP.NET Core MVC Project
Creating the Data Model Class
Configuring Services and Middleware
Adding a Controller and View
Adding the Bootstrap CSS Framework
Configuring the HTTP Port
Running the Example Application
Adding and Configuring Entity Framework Core
Adding the NuGet Package
Creating the Database Context Class
Preparing the Entity Class
Updating the Controller
Configuring the Database Provider
Defining the Connection String
Configuring the Application
Configuring Entity Framework Core Logging
Generating and Applying the Migration
Populating the Database
Starting the Example Application
Implementing the Repository Pattern
Defining the Repository Interface and Implementation Class
Avoiding the IEnumerable vs IQueryable Pitfall
Understanding and Avoiding the Additional Query Problem
Hiding the Data Operations
Completing the Example MVC Application
Completing the Repository
Adding the Action Methods
Updating and Adding Views
Summary
Chapter 12: Performing Data Operations
Preparing for This Chapter
Starting the Example Application
Reading Data
Reading an Object by Key
Querying All Objects
Querying for Specific Objects
Storing New Data
Understanding Key Assignment
Updating Data
Updating a Complete Object
Querying the Existing Data Before Updating
Understanding Change Detection
Updating in a Single Database Operation
Deleting Data
Summary
Chapter 13: Understanding Migrations
Preparing for This Chapter
Understanding Migrations
Working with the Initial Migration
Understanding the Migration Upgrade
Understanding the Migration Downgrade
Examining the Migration SQL
Applying the Migration
Checking the Migration
Seeding the Database and Running the Application
Creating Additional Migrations
Adding Another Property to the Data Model
Managing Migrations
Listing Migrations
Applying All Migrations
Updating to a Specific Migration
Removing a Migration
Resetting the Database
Working with Multiple Databases
Extending the Data Model
Configuring the Application
Creating and Applying Migrations
Managing Migrations Programmatically
Creating the Migration Manager Class
Creating the Migrations Controller and View
Configuring the Application
Running the Migrations Manager
Seeding Databases Programmatically
Creating a Seeding Tool
Seeding During Startup
Summary
Chapter 14: Creating Data Relationships
Preparing for This Chapter
Creating a Relationship
Adding a Navigation Property
Creating the Migration
Querying and Displaying the Related Data
Updating the View to Display Related Data
Preparing the Database
Creating and Updating Related Data
Creating a New Supplier When Creating a New Product
Updating a Supplier when Updating a Product
Deleting Related Data
Creating a Required Relationship
Creating a Foreign Key Property
Dropping the Database and Preparing the Seed Data
Updating and Seeding the Database
Understanding the Required Relationship Delete Operation
Querying for Multiple Relationships
Updating and Seeding the Database
Querying the Chain of Navigation Properties
Summary
Chapter 15: Working with Relationships Part 1
Preparing for This Chapter
Directly Accessing Related Data
Promoting Related Data
Consuming the Promoted Data
Accessing Related Data Using a Type Parameter
Completing a Data Relationship
Querying Related Data in a One-to-Many Relationship
Querying for All Related Data
Querying Using Explicit Loading
Querying Using the Fixing Up Feature
Understanding the Fixing Up Pitfall
Working with Related Data in a One-to-Many Relationship
Updating Related Objects
Creating New Related Objects
Changing Relationships
Simplifying the Relationship Change Code
Further Simplifying the Relationship Change Code
Summary
Chapter 16: Working with Relationship Part 2
Preparing for This Chapter
Completing a One-to-One Relationship
Defining the Navigation Property
Selecting the Dependent Entity Class
Creating and Applying the Migration
Working with One-to-One Relationships
Querying Related Data in a One-to-One Relationship
Updating the Database and Running the Application
Creating and Updating Related Objects
Changing One-to-One Relationships
Changing a Required One-to-One Relationship
Changing an Optional One-to-One Relationship
Defining Many-to-Many Relationships
Creating the Junction Class
Completing the Many-to-Many Relationship
Preparing the Application
Querying for Many-to-Many Data
Managing Many-to-Many Relationships
Summary
Chapter 17: Scaffolding an Existing Database
Preparing for This Chapter
Understanding the Example Existing Database
Connecting to the Database Server
Creating the Database
Creating the Colors Table
Creating the Shoes Table
Creating the SalesCampaigns Table
Creating the Categories and ShoeCategoryJunction Tables
Creating the ASP.NET Core MVC Project
Adding the Tools NuGet Package
Configuring ASP.NET Core Middleware and Services
Adding a Controller and View and Installing Bootstrap
Testing the Example Application
Scaffolding an Existing Database
Performing the Scaffold Process
Using a Scaffolded Data Model in the ASP.NET Core MVC
Creating the Configuration File
Updating the Context Class
Registering Middleware and Services
Updating the Controller and View
Responding to Database Changes
Modifying the Database
Updating the Data Model
Updating the Context Class
Updating the Controllers and Views
Adding Persistent Data Model Features
Summary
Chapter 18: Manually Modeling a Database
Preparing for This Chapter
Creating a Manual Data Model
Creating the Context and Entity Classes
Creating the Controller and View
Understanding the Basic Data Model Conventions
Overriding the Data Model Conventions
Using Attributes to Override Data Model Conventions
Using the Fluent API to Override Model Conventions
Using the Customized Data Model
Modeling Relationships
Overriding the Relationship Conventions Using Attributes
Overriding the Relationship Conventions Using the Fluent API
Completing the Data Model
Using the Manually Created Data Model
Querying Data in a Manually Created Data Model
Updating Data in a Manually Created Data Model
Creating the Partial Views
Creating the Editor View
Summary
Part III: Advanced Entity Framework Core 2
Chapter 19: Working with Keys
Preparing for This Chapter
Creating the Data Model
Creating the Controller and Views
Configuring the Application
Creating the Database and Testing the Application
Managing Key Generation
Understanding the Identity Strategy
Understanding the Hi-Lo Key Strategy
Using the Hi-Lo Strategy
Understanding Hi-Lo Key Exhaustion
Working with Natural Keys
Ensuring Unique Values for Natural Keys
Creating an Alternate Key
Using Natural Keys as Primary Keys
Creating Composite Keys
Summary
Chapter 20: Queries
Preparing for This Chapter
Managing Change Tracking for Query Results
Removing Individual Objects from Change Tracking
Changing the Default Change Tracking Behavior
Using a Query Filter
Overriding a Query Filter
Querying Using Search Patterns
Making Asynchronous Queries
Explicitly Compiling Queries
Avoiding the Client Evaluation Pitfall
Throwing a Client Evaluation Exception
Summary
Chapter 21: Storing Data
Preparing for This Chapter
Specifying SQL Data Types
Specifying a Maximum Length
Updating the Database
Validating or Formatting Data Values
Avoiding the Backing Field Selective Update Pitfall
Hiding Data Values from the MVC Application
Accessing Shadow Property Values
Including Shadow Properties in Queries
Setting Default Values
Displaying the Default Value
Detecting Concurrent Updates
Using Concurrency Tokens
Using a Row Version to Detect Concurrent Updates
Summary
Chapter 22: Deleting Data
Preparing for This Chapter
Understanding Delete Constraints
Configuring the Delete Behavior
Using the Cascade Delete Behavior
Setting Foreign Keys to Null
Relying on the Database Server to Change Foreign Keys
Relying on Entity Framework Core to Update Foreign Keys
Using a Query to Load Related Data
Avoiding Related Data Query
Taking Control of the Delete Operation
Re-creating the Cascade Behavior
Re-creating the Set Null Behavior
Reinstating the Soft-Delete Feature
Summary
Chapter 23: Using Database Server Features
Preparing for This Chapter
Using SQL Directly
Querying Using SQL
Querying Using Parameters
Composing Complex Queries
Using Raw SQL to Query Stored Procedures
Composing Complex Queries with Views
Composing Complex Queries Using Table-Valued Functions
Calling Stored Procedures or Other Operations
Using Server-Generated Values
Using Database Server–Generated Default Values
Incorporating Sequential Values
Computing Values in the Database
Querying Using a Computed Column
Modeling Automatically Generated Values
Summary
Chapter 24: Using Transactions
Preparing for This Chapter
Understanding the Default Behavior
Performing Independent Changes
Disabling Automatic Transactions
Using Explicit Transactions
Including Other Operations in a Transaction
Changing the Transaction Isolation Level
Understanding Dirty Reads, Phantom Rows, and Nonrepeatable Reads
Summary
Index