鼎鼎知识库
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

18.创建本地数据库迁移.md 5.3KB

添加数据模型类

  • 模型类,在Model中添加。例如Movie类 ``` 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; }
}

} ``` 脚手架电影模型

  • 电影模型是搭建的。也就是说,脚手架工具为电影模型生成用于创建,读取,更新和删除(CRUD)操作的页面。
  • 在Solution Explorer中,右键单击Controllers文件夹> Add> New Scaffolded Item
  • 在Add Scaffold对话框中,使用Entity Framework> Add选择带视图的MVC Controller。
  • 完成添加控制器对话框:
    • 型号类: 电影(MvcMovie.Models)
    • 数据上下文类:选择+图标并添加默认的MvcMovie.Models.MvcMovieContext

初始迁移数据库

  • 添加初始迁移
    • 从Tools菜单中,选择NuGet Package Manager > Package Manager Console(PMC)。
    • 在PMC中,输入以下命令:Add-Migration Initial / Update-Database

在.net core 中使用数据库

  • 该MvcMovieContext对象处理连接到数据库和将Movie对象映射到数据库记录的任务。数据库上下文在Startup.cs文件的方法中使用Dependency Injection容器注册:ConfigureServices

    public void ConfigureServices(IServiceCollection services)
    {
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies 
        // is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });
    
    
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    
    services.AddDbContext<MvcMovieContext>(options =>
         options.UseSqlServer(Configuration.GetConnectionString("MvcMovieContext")));
    }
    
  • ASP.NET核心配置系统读取ConnectionString。对于本地开发,它从appsettings.json文件获取连接字符串: "ConnectionStrings": { "MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-2;Trusted_Connection=True;MultipleActiveResultSets=true" }

种子数据库

  • 创建一个SeedData在Models文件夹中命名的新类 ``` using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Linq;

namespace MvcMovie.Models {

public static class SeedData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (var context = new MvcMovieContext(
            serviceProvider.GetRequiredService<
                DbContextOptions<MvcMovieContext>>()))
        {
            // Look for any movies.
            if (context.Movie.Any())
            {
                return;   // DB has been seeded
            }

            context.Movie.AddRange(
                new Movie
                {
                    Title = "When Harry Met Sally",
                    ReleaseDate = DateTime.Parse("1989-2-12"),
                    Genre = "Romantic Comedy",
                    Price = 7.99M
                },

                new Movie
                {
                    Title = "Ghostbusters ",
                    ReleaseDate = DateTime.Parse("1984-3-13"),
                    Genre = "Comedy",
                    Price = 8.99M
                },

                new Movie
                {
                    Title = "Ghostbusters 2",
                    ReleaseDate = DateTime.Parse("1986-2-23"),
                    Genre = "Comedy",
                    Price = 9.99M
                },

                new Movie
                {
                    Title = "Rio Bravo",
                    ReleaseDate = DateTime.Parse("1959-4-15"),
                    Genre = "Western",
                    Price = 3.99M
                }
            );
            context.SaveChanges();
        }
    }
}

}



向模型中添加一个新字段
- 将Rating属性添加到Models / Movie.cs:

public class Movie {

public int Id { get; set; }
public string Title { get; set; }

[Display(Name = "Release Date")]
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }

[Column(TypeName = "decimal(18, 2)")]
public decimal Price { get; set; }
public string Rating { get; set; }

}

- 因为您已向类添加了新字段,所以Movie需要更新绑定白名单,以便包含此新属性。在MoviesController.cs中,更新[Bind]for Create和Editaction方法的Rating属性以包含属性:

[Bind(“Id,Title,ReleaseDate,Genre,Price,Rating”)] ```

  • 更新视图模板,以便Rating在浏览器视图中显示,创建和编辑新属性。

编辑/Views/Movies/Index.cshtml文件并添加一个Rating字段:

  • 使用字段更新/Views/Movies/Create.cshtmlRating。
  • 更新SeedData类,以便为新列提供值。示例更改如下所示,但您需要对每个更改进行此更改new Movie。

  • 在PMC中,输入以下命令:Add-Migration Rating/Update-Database.