Skip to content

Commit 40beeaa

Browse files
authored
EF MVC for 2.0 (#4000)
1 parent e742f8c commit 40beeaa

File tree

97 files changed

+899
-888
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

97 files changed

+899
-888
lines changed

aspnetcore/data/ef-mvc/advanced.md

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ uid: data/ef-mvc/advanced
1717

1818
By [Tom Dykstra](https://github.com/tdykstra) and [Rick Anderson](https://twitter.com/RickAndMSFT)
1919

20-
The Contoso University sample web application demonstrates how to create ASP.NET Core 1.0 MVC web applications using Entity Framework Core 1.0 and Visual Studio 2015. For information about the tutorial series, see [the first tutorial in the series](intro.md).
20+
The Contoso University sample web application demonstrates how to create ASP.NET Core MVC web applications using Entity Framework Core and Visual Studio. For information about the tutorial series, see [the first tutorial in the series](intro.md).
2121

22-
In the previous tutorial you implemented table-per-hierarchy inheritance. This tutorial introduces several topics that are useful to be aware of when you go beyond the basics of developing ASP.NET web applications that use Entity Framework Core.
22+
In the previous tutorial, you implemented table-per-hierarchy inheritance. This tutorial introduces several topics that are useful to be aware of when you go beyond the basics of developing ASP.NET Core web applications that use Entity Framework Core.
2323

2424
## Raw SQL Queries
2525

@@ -110,20 +110,28 @@ Run the application in debug mode, and go to the Details page for a student.
110110
Go to the **Output** window showing debug output, and you see the query:
111111

112112
```
113-
Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory:Information: Executed DbCommand (225ms) [Parameters=[@__id_0='?'], CommandType='Text', CommandTimeout='30']
114-
SELECT [e].[EnrollmentID], [e].[CourseID], [e].[Grade], [e].[StudentID], [c].[CourseID], [c].[Credits], [c].[DepartmentID], [c].[Title]
115-
FROM [Enrollment] AS [e]
113+
Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (56ms) [Parameters=[@__id_0='?'], CommandType='Text', CommandTimeout='30']
114+
SELECT TOP(2) [s].[ID], [s].[Discriminator], [s].[FirstName], [s].[LastName], [s].[EnrollmentDate]
115+
FROM [Person] AS [s]
116+
WHERE ([s].[Discriminator] = N'Student') AND ([s].[ID] = @__id_0)
117+
ORDER BY [s].[ID]
118+
Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (122ms) [Parameters=[@__id_0='?'], CommandType='Text', CommandTimeout='30']
119+
SELECT [s.Enrollments].[EnrollmentID], [s.Enrollments].[CourseID], [s.Enrollments].[Grade], [s.Enrollments].[StudentID], [e.Course].[CourseID], [e.Course].[Credits], [e.Course].[DepartmentID], [e.Course].[Title]
120+
FROM [Enrollment] AS [s.Enrollments]
121+
INNER JOIN [Course] AS [e.Course] ON [s.Enrollments].[CourseID] = [e.Course].[CourseID]
116122
INNER JOIN (
117-
SELECT DISTINCT TOP(2) [s].[ID]
118-
FROM [Person] AS [s]
119-
WHERE ([s].[Discriminator] = N'Student') AND ([s].[ID] = @__id_0)
120-
ORDER BY [s].[ID]
121-
) AS [s0] ON [e].[StudentID] = [s0].[ID]
122-
INNER JOIN [Course] AS [c] ON [e].[CourseID] = [c].[CourseID]
123-
ORDER BY [s0].[ID]
123+
SELECT TOP(1) [s0].[ID]
124+
FROM [Person] AS [s0]
125+
WHERE ([s0].[Discriminator] = N'Student') AND ([s0].[ID] = @__id_0)
126+
ORDER BY [s0].[ID]
127+
) AS [t] ON [s.Enrollments].[StudentID] = [t].[ID]
128+
ORDER BY [t].[ID]
124129
```
125130

126-
You'll notice something here that might surprise you: the SQL selects up to 2 rows (`TOP(2)`). The `SingleOrDefaultAsync` method doesn't resolve to one row on the server. If the Where clause matches multiple rows, the method must return null, so EF only has to select a maximum of 2 rows, because if 3 or more match the Where clause, the result from the `SingleOrDefault` method is the same as if 2 rows match.
131+
You'll notice something here that might surprise you: the SQL selects up to 2 rows (`TOP(2)`) from the Person table. The `SingleOrDefaultAsync` method doesn't resolve to 1 row on the server. Here's why:
132+
133+
* If the query would return multiple rows, the method returns null.
134+
* To determine whether the query would return multiple rows, EF has to check if it returns at least 2.
127135

128136
Note that you don't have to use debug mode and stop at a breakpoint to get logging output in the **Output** window. It's just a convenient way to stop the logging at the point you want to look at the output. If you don't do that, logging continues and you have to scroll back to find the parts you're interested in.
129137

aspnetcore/data/ef-mvc/complex-data-model.md

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ uid: data/ef-mvc/complex-data-model
1717

1818
By [Tom Dykstra](https://github.com/tdykstra) and [Rick Anderson](https://twitter.com/RickAndMSFT)
1919

20-
The Contoso University sample web application demonstrates how to create ASP.NET Core 1.1 MVC web applications using Entity Framework Core 1.1 and Visual Studio 2017. For information about the tutorial series, see [the first tutorial in the series](intro.md).
20+
The Contoso University sample web application demonstrates how to create ASP.NET Core MVC web applications using Entity Framework Core and Visual Studio. For information about the tutorial series, see [the first tutorial in the series](intro.md).
2121

22-
In the previous tutorials you worked with a simple data model that was composed of three entities. In this tutorial you'll add more entities and relationships and you'll customize the data model by specifying formatting, validation, and database mapping rules.
22+
In the previous tutorials, you worked with a simple data model that was composed of three entities. In this tutorial, you'll add more entities and relationships and you'll customize the data model by specifying formatting, validation, and database mapping rules.
2323

2424
When you're finished, the entity classes will make up the completed data model that's shown in the following illustration:
2525

@@ -83,6 +83,9 @@ Save your changes and build the project. Then open the command window in the pro
8383

8484
```console
8585
dotnet ef migrations add MaxLengthOnNames
86+
```
87+
88+
```console
8689
dotnet ef database update
8790
```
8891

@@ -110,6 +113,9 @@ Save your changes and build the project. Then open the command window in the pro
110113

111114
```console
112115
dotnet ef migrations add ColumnFirstName
116+
```
117+
118+
```console
113119
dotnet ef database update
114120
```
115121

@@ -420,11 +426,6 @@ dotnet ef migrations add ComplexDataModel
420426
You get a warning about possible data loss.
421427

422428
```text
423-
Build succeeded.
424-
0 Warning(s)
425-
0 Error(s)
426-
427-
Time Elapsed 00:00:11.58
428429
An operation was scaffolded that may result in the loss of data. Please review the migration for accuracy.
429430
Done. To undo this action, use 'ef migrations remove'
430431
```

aspnetcore/data/ef-mvc/concurrency.md

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ uid: data/ef-mvc/concurrency
1717

1818
By [Tom Dykstra](https://github.com/tdykstra) and [Rick Anderson](https://twitter.com/RickAndMSFT)
1919

20-
The Contoso University sample web application demonstrates how to create ASP.NET Core 1.1 MVC web applications using Entity Framework Core 1.1 and Visual Studio 2017. For information about the tutorial series, see [the first tutorial in the series](intro.md).
20+
The Contoso University sample web application demonstrates how to create ASP.NET Core MVC web applications using Entity Framework Core and Visual Studio. For information about the tutorial series, see [the first tutorial in the series](intro.md).
2121

22-
In earlier tutorials you learned how to update data. This tutorial shows how to handle conflicts when multiple users update the same entity at the same time.
22+
In earlier tutorials, you learned how to update data. This tutorial shows how to handle conflicts when multiple users update the same entity at the same time.
2323

2424
You'll create web pages that work with the Department entity and handle concurrency errors. The following illustrations show the Edit and Delete pages, including some messages that are displayed if a concurrency conflict occurs.
2525

@@ -104,6 +104,9 @@ Save your changes and build the project, and then enter the following commands i
104104

105105
```console
106106
dotnet ef migrations add RowVersion
107+
```
108+
109+
```console
107110
dotnet ef database update
108111
```
109112

@@ -175,13 +178,13 @@ In *Views/Departments/Edit.cshtml*, make the following changes:
175178

176179
* Add a "Select Administrator" option to the drop-down list.
177180

178-
[!code-html[Main](intro/samples/cu/Views/Departments/Edit.cshtml?highlight=15,41-43)]
181+
[!code-html[Main](intro/samples/cu/Views/Departments/Edit.cshtml?highlight=16,34-36)]
179182

180183
## Test concurrency conflicts in the Edit page
181184

182185
Run the site and click Departments to go to the Departments Index page.
183186

184-
Right click the **Edit** hyperlink for the English department and select **Open in new tab**, then click the **Edit** hyperlink for the English department. The two browser tabs now display the same information.
187+
Right-click the **Edit** hyperlink for the English department and select **Open in new tab**, then click the **Edit** hyperlink for the English department. The two browser tabs now display the same information.
185188

186189
Change a field in the first browser tab and click **Save**.
187190

@@ -238,7 +241,7 @@ If a concurrency error is caught, the code redisplays the Delete confirmation pa
238241

239242
In *Views/Department/Delete.cshtml*, replace the scaffolded code with the following code that adds an error message field and hidden fields for the DepartmentID and RowVersion properties. The changes are highlighted.
240243

241-
[!code-html[Main](intro/samples/cu/Views/Departments/Delete.cshtml?highlight=9,38,43-44)]
244+
[!code-html[Main](intro/samples/cu/Views/Departments/Delete.cshtml?highlight=9,38,44)]
242245

243246
This makes the following changes:
244247

@@ -248,7 +251,7 @@ This makes the following changes:
248251

249252
* Removes the RowVersion field.
250253

251-
* Adds hidden fields for the `DepartmentID` and `RowVersion` properties.
254+
* Adds a hidden field for the `RowVersion` property.
252255

253256
Run the Departments Index page. Right click the **Delete** hyperlink for the English department and select **Open in new tab**, then in the first tab click the **Edit** hyperlink for the English department.
254257

@@ -272,7 +275,7 @@ Replace the code in *Views/Departments/Details.cshtml* to delete the RowVersion
272275

273276
Replace the code in *Views/Departments/Create.cshtml* to add a Select option to the drop-down list.
274277

275-
[!code-html[Main](intro/samples/cu/Views/Departments/Create.cshtml?highlight=38-40)]
278+
[!code-html[Main](intro/samples/cu/Views/Departments/Create.cshtml?highlight=32-34)]
276279

277280
## Summary
278281

aspnetcore/data/ef-mvc/crud.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ uid: data/ef-mvc/crud
1616

1717
By [Tom Dykstra](https://github.com/tdykstra) and [Rick Anderson](https://twitter.com/RickAndMSFT)
1818

19-
The Contoso University sample web application demonstrates how to create ASP.NET Core 1.1 MVC web applications using Entity Framework Core 1.1 and Visual Studio 2017. For information about the tutorial series, see [the first tutorial in the series](intro.md).
19+
The Contoso University sample web application demonstrates how to create ASP.NET Core MVC web applications using Entity Framework Core and Visual Studio. For information about the tutorial series, see [the first tutorial in the series](intro.md).
2020

21-
In the previous tutorial you created an MVC application that stores and displays data using the Entity Framework and SQL Server LocalDB. In this tutorial you'll review and customize the CRUD (create, read, update, delete) code that the MVC scaffolding automatically creates for you in controllers and views.
21+
In the previous tutorial, you created an MVC application that stores and displays data using the Entity Framework and SQL Server LocalDB. In this tutorial, you'll review and customize the CRUD (create, read, update, delete) code that the MVC scaffolding automatically creates for you in controllers and views.
2222

2323
> [!NOTE]
2424
> It's a common practice to implement the repository pattern in order to create an abstraction layer between your controller and the data access layer. To keep these tutorials simple and focused on teaching how to use the Entity Framework itself, they don't use repositories. For information about repositories with EF, see [the last tutorial in this series](advanced.md).
@@ -49,7 +49,7 @@ The `AsNoTracking` method improves performance in scenarios where the entities r
4949

5050
The key value that is passed to the `Details` method comes from *route data*. Route data is data that the model binder found in a segment of the URL. For example, the default route specifies controller, action, and id segments:
5151

52-
[!code-csharp[Main](intro/samples/cu/Startup.cs?name=snippet_RouteAndSeed&highlight=5)]
52+
[!code-csharp[Main](intro/samples/cu/Startup.cs?name=snippet_Route&highlight=5)]
5353

5454
In the following URL, the default route maps Instructor as the controller, Index as the action, and 1 as the id; these are route data values.
5555

@@ -153,7 +153,7 @@ The code in *Views/Students/Create.cshtml* uses `label`, `input`, and `span` (fo
153153

154154
Run the page by selecting the **Students** tab and clicking **Create New**.
155155

156-
Enter names and an invalid date and click **Create** to see the error message.
156+
Enter names and a date. Try entering an invalid date if your browser lets you do that. (Some browsers force you to use a date picker.) Then click **Create** to see the error message.
157157

158158
![Date validation error](crud/_static/date-error.png)
159159

aspnetcore/data/ef-mvc/inheritance.md

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ uid: data/ef-mvc/inheritance
1717

1818
By [Tom Dykstra](https://github.com/tdykstra) and [Rick Anderson](https://twitter.com/RickAndMSFT)
1919

20-
The Contoso University sample web application demonstrates how to create ASP.NET Core 1.1 MVC web applications using Entity Framework Core 1.1 and Visual Studio 2017. For information about the tutorial series, see [the first tutorial in the series](intro.md).
20+
The Contoso University sample web application demonstrates how to create ASP.NET Core MVC web applications using Entity Framework Core and Visual Studio. For information about the tutorial series, see [the first tutorial in the series](intro.md).
2121

22-
In the previous tutorial you handled concurrency exceptions. This tutorial will show you how to implement inheritance in the data model.
22+
In the previous tutorial, you handled concurrency exceptions. This tutorial will show you how to implement inheritance in the data model.
2323

2424
In object-oriented programming, you can use inheritance to facilitate code reuse. In this tutorial, you'll change the `Instructor` and `Student` classes so that they derive from a `Person` base class which contains properties such as `LastName` that are common to both instructors and students. You won't add or change any web pages, but you'll change some of the code and those changes will be automatically reflected in the database.
2525

@@ -86,15 +86,7 @@ Save your changes and build the project. Then open the command window in the pro
8686
dotnet ef migrations add Inheritance
8787
```
8888

89-
Run the `database update` command:.
90-
91-
```console
92-
dotnet ef database update
93-
```
94-
95-
The command will fail at this point because you have existing data that migrations doesn't know how to handle. You get an error message like the following one:
96-
97-
> The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_CourseAssignment_Person_InstructorID". The conflict occurred in database "ContosoUniversity09133", table "dbo.Person", column 'ID'.
89+
Don't run the `database update` command yet. That command will result in lost data because it will drop the Instructor table and rename the Student table to Person. You need to provide custom code to preserve existing data.
9890

9991
Open *Migrations\<timestamp>_Inheritance.cs* and replace the `Up` method with the following code:
10092

@@ -122,7 +114,7 @@ This code takes care of the following database update tasks:
122114

123115
(If you had used GUID instead of integer as the primary key type, the student primary key values wouldn't have to change, and several of these steps could have been omitted.)
124116

125-
Run the `database update` command again:
117+
Run the `database update` command:
126118

127119
```console
128120
dotnet ef database update

0 commit comments

Comments
 (0)