学海无涯

导航

统计

向数据库中添加种子数据

在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);
}

 

posted on   宁静致远.  阅读(29)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示