ASP.NET Core5.0探索1.3_添加模型

1.先添加个用于测试的类
右键单击 Models 文件夹,然后单击“添加” > “类” 。 将文件命名为 Movie.cs。

using System;
using System.ComponentModel.DataAnnotations;

namespace MvcMovie.Models
{
    
    
    public class Movie
    {
    
    
        public int Id {
    
     get; set; }
        public string Title {
    
     get; set; }

        [DataType(DataType.Date)]
        public DateTime ReleaseDate {
    
     get; set; }
        public string Genre {
    
     get; set; }
        public decimal Price {
    
     get; set; }
    }
}

2.从“工具”菜单中,选择“NuGet 包管理器”>“包管理器控制台”(PMC)。
输入命令如下
Install-Package Microsoft.EntityFrameworkCore.SqlServer
命令添加 EF Core SQL Server 提供程序。 提供程序包将 EF Core 包作为依赖项进行安装
3.创建数据库上下文
创建一个“Data”文件夹。
使用以下代码添加 Data/MvcMovieContext.cs 文件:

using Microsoft.EntityFrameworkCore;
using MvcMovie.Models;

namespace MvcMovie.Data
{
    
    
    public class MvcMovieContext : DbContext
    {
    
    
        public MvcMovieContext (DbContextOptions<MvcMovieContext> options)
            : base(options)
        {
    
    
        }

        public DbSet<Movie> Movie {
    
     get; set; }
    }
}

4.注册数据库上下文
红色标志表重点
在这里插入图片描述
代码

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NETCore.Data;


namespace NETCore
{
    
    
    public class Startup
    {
    
    
        public Startup(IConfiguration configuration)
        {
    
    
            Configuration = configuration;
        }

        // IConfiguration 是用来加载配置值的,可以加载内存键值对、JSON或XML配置文件,我们通常用来加载缺省的appsettings.json .

        public IConfiguration Configuration {
    
     get; }
        //此方法由运行时调用。使用此方法向容器添加服务。
        public void ConfigureServices(IServiceCollection services)
        {
    
    
            //你也可以把services.AddControllers换成下面任意一句话。services.AddMvc() //加载整个mvc框架所有功能 services.AddMvcCore() //加载mvc框架的核心功能,
            //    services.AddMvc();
            services.AddControllersWithViews();
            services.AddDbContext<MvcMovieContext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString("MvcMovieContext")));
        }

        //此方法由运行时调用。使用此方法配置HTTP请求管道。
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
    
    
            if (env.IsDevelopment())
            {
    
    
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            //app.UseEndpoints(endpoints =>
            //{
    
    
            //    endpoints.MapGet("/", async context =>
            //    {
    
    
            //        await context.Response.WriteAsync("Hello World!");
            //    });
            //});
            app.UseEndpoints(endpoints =>
            {
    
    
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Movies}/{action=Index}/{id?}");//后面的 ?(id? 中)表示 id 参数可选。
            });
        }
    }
}

5.添加数据库连接字符串
将连接字符串添加到 appsettings.json 文件中:
在这里插入图片描述
代码

  "ConnectionStrings": {
    
    
    "MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=TestNetCoreDB;User ID=sa;Password=123456;Trusted_Connection=True;MultipleActiveResultSets=true"
  }

6.新搭建基架的项目-在控制器中
在这里插入图片描述
在这里插入图片描述
模型类:Movie (MvcMovie.Models)
数据上下文类:MvcMovieContext (MvcMovie.Data)
在这里插入图片描述
7.使用 EF Core 迁移功能来创建数据库。
从“工具”菜单中,选择“NuGet 包管理器”>“包管理器控制台”(PMC)。
在 PMC 中,输入以下命令:
Add-Migration InitialCreate
Update-Database

数据库更新命令生成以下警告:
No type was specified for the decimal column ‘Price’ on entity type ‘Movie’. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values using ‘HasColumnType()’.
你可以忽略该警告,它将后面的教程中得到修复。

完成后生成如下文件,运行即可
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/q1923408717/article/details/115089438