常用词汇:
GUID: 默认值设置 有序:NEWSEQUENTIALID() 无序:NEWID()
1.1.根据数据库生成实体类和数据连接,放在实体类所在项目生成,几乎不用改动,更方便.
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Test
1.2startup数据库连接配置与appsettings.json配置
public StartupDevelopment(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyContext")));
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "ConnectionStrings": { "MyContext": "Server=.;Database=BlogDemo;Trusted_Connection=True;MultipleActiveResultSets=true" } }
1.HTTPS HSTS
services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 5001; }); services.AddHsts(options => { options.Preload = true; options.IncludeSubDomains = true; options.MaxAge = TimeSpan.FromDays(60); options.ExcludedHosts.Add("example.com"); options.ExcludedHosts.Add("www.example.com"); });
2. .UseStartup<Startup>(); 使用基于环境的类
.UseStartup(typeof(StartupDevelopment).GetTypeInfo().Assembly.FullName);
3.表为空填写默认数据,在program.cs修改如下
// CreateWebHostBuilder(args).Build().Run(); 将词句注释掉, var host= CreateWebHostBuilder(args).Build(); using (var scope=host.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService<ILoggerFactory>(); try { var myContext = services.GetRequiredService<MyContext>(); MyContextSeed.SeedAsync(myContext, loggerFactory).Wait(); } catch (Exception e) { var logger = loggerFactory.CreateLogger<Program>(); logger.LogError(e,"填写默认数据失败"); } } host.Run();
3.2数据表为
namespace BlogDemo.Infrastructure.Database { public class MyContextSeed { public static async Task SeedAsync(MyContext myContext, ILoggerFactory loggerFactory, int retry = 0) { int retryForAvailability = retry; try { // TODO: Only run this if using a real database // myContext.Database.Migrate(); if (!myContext.Posts.Any()) { myContext.Posts.AddRange( new List<Post>{ new Post{ Title = "Post Title 1", Body = "Post Body 1", Author = "Dave", LastModified = DateTime.Now }, new Post{ Title = "Post Title 2", Body = "Post Body 2", Author = "Dave", LastModified = DateTime.Now }, new Post{ Title = "Post Title 3", Body = "Post Body 3", Author = "Dave", LastModified = DateTime.Now } } ); await myContext.SaveChangesAsync(); } } catch (Exception ex) { if (retryForAvailability < 10) { retryForAvailability++; var logger = loggerFactory.CreateLogger<MyContextSeed>(); logger.LogError(ex.Message); await SeedAsync(myContext, loggerFactory, retryForAvailability); } } } } }