[!INCLUDEadding-model1]
- Add a class to the Models folder named Movie.cs.
- Add the following code to the Models/Movie.cs file:
[!code-csharpMain]
1: //#define MovieNoEF
2: #if MovieNoEF
3: #region snippet_1
4: using System;
5:
6: namespace MvcMovie.Models
7: {
8: public class Movie
9: {
10: public int ID { get; set; }
11: public string Title { get; set; }
12: public DateTime ReleaseDate { get; set; }
13: public string Genre { get; set; }
14: public decimal Price { get; set; }
15: }
16: }
17: #endregion
18: #endif
The ID
field is required by the database for the primary key.
Build the app to verify you don’t have any errors, and you’ve finally added a Model to your MVC app.
Prepare the project for scaffolding
Add the following highlighted NuGet packages to the MvcMovie.csproj file:
[!code-csharpMain]
1: <Project Sdk="Microsoft.NET.Sdk.Web">
2: <PropertyGroup>
3: <TargetFramework>netcoreapp2.0</TargetFramework>
4: </PropertyGroup>
5: <ItemGroup>
6: <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
7: <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0" />
8: </ItemGroup>
9: <ItemGroup>
10: <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
11: <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
12: </ItemGroup>
13: </Project>
- Save the file and select Restore to the Info message “There are unresolved dependencies”.
Create a Models/MvcMovieContext.cs file and add the following
MvcMovieContext
class:[!code-csharpMain]
1: using Microsoft.EntityFrameworkCore;
2:
3: namespace MvcMovie.Models
4: {
5: public class MvcMovieContext : DbContext
6: {
7: public MvcMovieContext (DbContextOptions<MvcMovieContext> options)
8: : base(options)
9: {
10: }
11:
12: public DbSet<MvcMovie.Models.Movie> Movie { get; set; }
13: }
14: }
Open the Startup.cs file and add two usings:
[!code-csharpMain]
1: using Microsoft.AspNetCore.Builder;
2: using Microsoft.AspNetCore.Hosting;
3: using Microsoft.Extensions.Configuration;
4: using Microsoft.Extensions.DependencyInjection;
5: using Microsoft.Extensions.Logging;
6: #region snippet1
7: using Microsoft.EntityFrameworkCore;
8: using MvcMovie.Models;
9:
10: namespace MvcMovie
11: {
12: public class Startup
13: {
14: #endregion
15: public Startup(IHostingEnvironment env)
16: {
17: var builder = new ConfigurationBuilder()
18: .SetBasePath(env.ContentRootPath)
19: .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
20: .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
21: .AddEnvironmentVariables();
22: Configuration = builder.Build();
23: }
24:
25: public IConfigurationRoot Configuration { get; }
26:
27: // This method gets called by the runtime. Use this method to add services to the container.
28: #region snippet2
29: public void ConfigureServices(IServiceCollection services)
30: {
31: // Add framework services.
32: services.AddMvc();
33:
34: services.AddDbContext<MvcMovieContext>(options =>
35: options.UseSqlite("Data Source=MvcMovie.db"));
36:
37: }
38: #endregion
39:
40: // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
41: public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
42: {
43: loggerFactory.AddConsole(Configuration.GetSection("Logging"));
44: loggerFactory.AddDebug();
45:
46: if (env.IsDevelopment())
47: {
48: app.UseDeveloperExceptionPage();
49: app.UseBrowserLink();
50: }
51: else
52: {
53: app.UseExceptionHandler("/Home/Error");
54: }
55:
56: app.UseStaticFiles();
57: #region snippet_seed
58: app.UseMvc(routes =>
59: {
60: routes.MapRoute(
61: name: "default",
62: template: "{controller=Movies}/{action=Index}/{id?}");
63: });
64:
65: DBinitialize.EnsureCreated(app.ApplicationServices);
66: SeedData.Initialize(app.ApplicationServices);
67: }
68: #endregion
69: }
70: }
Add the database context to the Startup.cs file:
[!code-csharpMain]
1: using Microsoft.AspNetCore.Builder;
2: using Microsoft.AspNetCore.Hosting;
3: using Microsoft.Extensions.Configuration;
4: using Microsoft.Extensions.DependencyInjection;
5: using Microsoft.Extensions.Logging;
6: #region snippet1
7: using Microsoft.EntityFrameworkCore;
8: using MvcMovie.Models;
9:
10: namespace MvcMovie
11: {
12: public class Startup
13: {
14: #endregion
15: public Startup(IHostingEnvironment env)
16: {
17: var builder = new ConfigurationBuilder()
18: .SetBasePath(env.ContentRootPath)
19: .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
20: .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
21: .AddEnvironmentVariables();
22: Configuration = builder.Build();
23: }
24:
25: public IConfigurationRoot Configuration { get; }
26:
27: // This method gets called by the runtime. Use this method to add services to the container.
28: #region snippet2
29: public void ConfigureServices(IServiceCollection services)
30: {
31: // Add framework services.
32: services.AddMvc();
33:
34: services.AddDbContext<MvcMovieContext>(options =>
35: options.UseSqlite("Data Source=MvcMovie.db"));
36:
37: }
38: #endregion
39:
40: // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
41: public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
42: {
43: loggerFactory.AddConsole(Configuration.GetSection("Logging"));
44: loggerFactory.AddDebug();
45:
46: if (env.IsDevelopment())
47: {
48: app.UseDeveloperExceptionPage();
49: app.UseBrowserLink();
50: }
51: else
52: {
53: app.UseExceptionHandler("/Home/Error");
54: }
55:
56: app.UseStaticFiles();
57: #region snippet_seed
58: app.UseMvc(routes =>
59: {
60: routes.MapRoute(
61: name: "default",
62: template: "{controller=Movies}/{action=Index}/{id?}");
63: });
64:
65: DBinitialize.EnsureCreated(app.ApplicationServices);
66: SeedData.Initialize(app.ApplicationServices);
67: }
68: #endregion
69: }
70: }
This tells Entity Framework which model classes are included in the data model. You’re defining one entity set of Movie objects, which will be represented in the database as a Movie table.
Build the project to verify there are no errors.
Scaffold the MovieController
Open a terminal window in the project folder and run the following commands:
dotnet restore
dotnet aspnet-codegenerator controller -name MoviesController -m Movie -dc MvcMovieContext --relativeFolderPath Controllers --useDefaultLayout --referenceScriptLibraries
[!NOTE] If you get an error when the scaffolding command runs, see issue 444 in the scaffolding repository for a workaround.
The scaffolding engine creates the following:
- A movies controller (Controllers/MoviesController.cs)
- Razor view files for Create, Delete, Details, Edit and Index pages (Views/Movies/*.cshtml)
The automatic creation of CRUD (create, read, update, and delete) action methods and views is known as scaffolding. You’ll soon have a fully functional web application that lets you manage a movie database.
[!INCLUDEadding-model 2x]
[!INCLUDEadding-model]
You now have a database and pages to display, edit, update and delete data. In the next tutorial, we’ll work with the database.
Additional resources
|