鼎鼎知识库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. > 添加数据模型类
  2. - 模型类,在Model中添加。例如Movie类
  3. ```
  4. using System;
  5. using System.ComponentModel.DataAnnotations;
  6. namespace MvcMovie.Models
  7. {
  8. public class Movie
  9. {
  10. public int Id { get; set; }
  11. public string Title { get; set; }
  12. [DataType(DataType.Date)]
  13. public DateTime ReleaseDate { get; set; }
  14. public string Genre { get; set; }
  15. public decimal Price { get; set; }
  16. }
  17. }
  18. ```
  19. > 脚手架电影模型
  20. - 电影模型是搭建的。也就是说,脚手架工具为电影模型生成用于创建,读取,更新和删除(CRUD)操作的页面。
  21. - 在Solution Explorer中,右键单击Controllers文件夹> Add> New Scaffolded Item
  22. - 在Add Scaffold对话框中,使用Entity Framework> Add选择带视图的MVC Controller。
  23. - 完成添加控制器对话框:
  24. - 型号类: 电影(MvcMovie.Models)
  25. - 数据上下文类:选择+图标并添加默认的MvcMovie.Models.MvcMovieContext
  26. > 初始迁移数据库
  27. - 添加初始迁移
  28. - 从Tools菜单中,选择NuGet Package Manager > Package Manager Console(PMC)。
  29. - 在PMC中,输入以下命令:Add-Migration Initial / Update-Database
  30. > 在.net core 中使用数据库
  31. - 该MvcMovieContext对象处理连接到数据库和将Movie对象映射到数据库记录的任务。数据库上下文在Startup.cs文件的方法中使用Dependency Injection容器注册:ConfigureServices
  32. ```
  33. public void ConfigureServices(IServiceCollection services)
  34. {
  35. services.Configure<CookiePolicyOptions>(options =>
  36. {
  37. // This lambda determines whether user consent for non-essential cookies
  38. // is needed for a given request.
  39. options.CheckConsentNeeded = context => true;
  40. options.MinimumSameSitePolicy = SameSiteMode.None;
  41. });
  42. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  43. services.AddDbContext<MvcMovieContext>(options =>
  44. options.UseSqlServer(Configuration.GetConnectionString("MvcMovieContext")));
  45. }
  46. ```
  47. - ASP.NET核心配置系统读取ConnectionString。对于本地开发,它从appsettings.json文件获取连接字符串:
  48. ```
  49. "ConnectionStrings": {
  50. "MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-2;Trusted_Connection=True;MultipleActiveResultSets=true"
  51. }
  52. ```
  53. > 种子数据库
  54. - 创建一个SeedData在Models文件夹中命名的新类
  55. ```
  56. using Microsoft.EntityFrameworkCore;
  57. using Microsoft.Extensions.DependencyInjection;
  58. using System;
  59. using System.Linq;
  60. namespace MvcMovie.Models
  61. {
  62. public static class SeedData
  63. {
  64. public static void Initialize(IServiceProvider serviceProvider)
  65. {
  66. using (var context = new MvcMovieContext(
  67. serviceProvider.GetRequiredService<
  68. DbContextOptions<MvcMovieContext>>()))
  69. {
  70. // Look for any movies.
  71. if (context.Movie.Any())
  72. {
  73. return; // DB has been seeded
  74. }
  75. context.Movie.AddRange(
  76. new Movie
  77. {
  78. Title = "When Harry Met Sally",
  79. ReleaseDate = DateTime.Parse("1989-2-12"),
  80. Genre = "Romantic Comedy",
  81. Price = 7.99M
  82. },
  83. new Movie
  84. {
  85. Title = "Ghostbusters ",
  86. ReleaseDate = DateTime.Parse("1984-3-13"),
  87. Genre = "Comedy",
  88. Price = 8.99M
  89. },
  90. new Movie
  91. {
  92. Title = "Ghostbusters 2",
  93. ReleaseDate = DateTime.Parse("1986-2-23"),
  94. Genre = "Comedy",
  95. Price = 9.99M
  96. },
  97. new Movie
  98. {
  99. Title = "Rio Bravo",
  100. ReleaseDate = DateTime.Parse("1959-4-15"),
  101. Genre = "Western",
  102. Price = 3.99M
  103. }
  104. );
  105. context.SaveChanges();
  106. }
  107. }
  108. }
  109. }
  110. ```
  111. > 向模型中添加一个新字段
  112. - 将Rating属性添加到Models / Movie.cs:
  113. ```
  114. public class Movie
  115. {
  116. public int Id { get; set; }
  117. public string Title { get; set; }
  118. [Display(Name = "Release Date")]
  119. [DataType(DataType.Date)]
  120. public DateTime ReleaseDate { get; set; }
  121. public string Genre { get; set; }
  122. [Column(TypeName = "decimal(18, 2)")]
  123. public decimal Price { get; set; }
  124. public string Rating { get; set; }
  125. }
  126. ```
  127. - 因为您已向类添加了新字段,所以Movie需要更新绑定白名单,以便包含此新属性。在MoviesController.cs中,更新[Bind]for Create和Editaction方法的Rating属性以包含属性:
  128. ```
  129. [Bind("Id,Title,ReleaseDate,Genre,Price,Rating")]
  130. ```
  131. - 更新视图模板,以便Rating在浏览器视图中显示,创建和编辑新属性。
  132. 编辑/Views/Movies/Index.cshtml文件并添加一个Rating字段:
  133. - 使用字段更新/Views/Movies/Create.cshtmlRating。
  134. - 更新SeedData类,以便为新列提供值。示例更改如下所示,但您需要对每个更改进行此更改new Movie。
  135. - 在PMC中,输入以下命令:Add-Migration Rating/Update-Database.