首页 > 数据库 >向数据库中添加种子数据

向数据库中添加种子数据

时间:2023-02-10 10:36:02浏览次数:43  
标签:Title Movie 数据库 DateTime Parse 添加 种子 using new

在Models目录下添加SeedData类

 1 using Microsoft.EntityFrameworkCore;
 2 using MvcMovie.Data;
 3 
 4 namespace MvcMovie.Models
 5 {
 6     public static class SeedData
 7     {
 8         public static void Initialize(IServiceProvider serviceProvider)
 9         {
10             using(var context=new MvcMovieContext(serviceProvider.GetRequiredService<DbContextOptions<MvcMovieContext>>()))
11             {
12                 if(context.Movie.Any())
13                 {
14                     return;//Movie表已经有数据了
15                 }
16                 context.Movie.AddRange(
17                new Movie
18                {
19                    Title = "When Harry Met Sally",
20                    ReleaseDate = DateTime.Parse("1989-2-12"),
21                    Genre = "Romantic Comedy",
22                    Price = 7.99M
23                },
24                new Movie
25                {
26                    Title = "Ghostbusters ",
27                    ReleaseDate = DateTime.Parse("1984-3-13"),
28                    Genre = "Comedy",
29                    Price = 8.99M
30                },
31                new Movie
32                {
33                    Title = "Ghostbusters 2",
34                    ReleaseDate = DateTime.Parse("1986-2-23"),
35                    Genre = "Comedy",
36                    Price = 9.99M
37                },
38                new Movie
39                {
40                    Title = "Rio Bravo",
41                    ReleaseDate = DateTime.Parse("1959-4-15"),
42                    Genre = "Western",
43                    Price = 3.99M
44                }
45            );
46                 context.SaveChanges();
47             }
48         }
49     }
50 }

在Program中添加以下代码:

var app = builder.Build();
using (var scope = app.Services.CreateScope())
{//向数据库添加种子数据
    var services = scope.ServiceProvider;
    SeedData.Initialize(services);
}

 

标签:Title,Movie,数据库,DateTime,Parse,添加,种子,using,new
From: https://www.cnblogs.com/friend/p/17108028.html

相关文章