直接通过代码创建数据库初始表。

        private static void CreateDbIfNotExists(IWebHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService<MediaContext>();
                    context.Database.EnsureCreated();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred creating the DB.");
                }
            }
        }


        //MediaContext:DbContext
        //省略其他,重写创建模型方法
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //映射创建表,如果表已经存在就不会再创建。
            modelBuilder.Entity<User>().ToTable("Tbl_User");
            modelBuilder.Entity<Attachment>().ToTable("Tbl_Attachment");
            modelBuilder.Entity<Role>().ToTable("Tbl_Role");
            modelBuilder.Entity<AlbumDetail>().ToTable("Tbl_AlbumDetail");
            modelBuilder.Entity<Album>().ToTable("Tbl_Album");
            modelBuilder.Entity<AlbumDetailModel>().ToView("V_AlbumDetail");
            modelBuilder.Entity<AlbumModel>().ToView("V_Album");
            try
            {
                //视图不能直接映射创建,所以这里直接用SQL语句来创建
                Database.ExecuteSqlRaw("CREATE VIEW \"V_Album\" AS select album.*,att.RemoteDomain,att.RelativePath from Tbl_Album album left join Tbl_Attachment att on album.ThumbnailId = att.Id WHERE NOT EXISTS (SELECT * FROM sqlite_master s WHERE s.type = 'view' AND name = 'V_Album')");

                Database.ExecuteSqlRaw("CREATE VIEW \"V_AlbumDetail\" AS select ad.*,( fa.RemoteDomain||'/' ||fa.RelativePath ) as Url, (ta.RemoteDomain||'/' ||ta.RelativePath ) as Thumbnail from Tbl_AlbumDetail ad inner join Tbl_Attachment fa on ad.AttachmentId=fa.Id inner join Tbl_Attachment ta on ad.ThumbnailId =ta.Id WHERE NOT EXISTS (SELECT * FROM sqlite_master s WHERE s.type = 'view' AND name = 'V_AlbumDetail')");

            }
            catch
            {

            }
        }


本文会经常更新,请阅读原文: https://huchengv5.gitee.io//post/asp.net-core-%E4%BD%BF%E7%94%A8EF-Core%E5%88%9B%E5%BB%BA%E5%88%9D%E5%A7%8B%E6%95%B0%E6%8D%AE%E5%BA%93.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

知识共享许可协议 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名胡承(包含链接: https://huchengv5.gitee.io/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系