【注意】:重载OnConfiguring和之前EF版本中的OnModelCreating创建模型不一样,OnModelCreating创建模型上下文只实例化一次,但是OnConfiguring每实例化一个上下文时都会被调用一次,所以OnConfiguring能充分利用上下文中的构造函数或者其他数据。


1 public static class DatabasePathHelper 2 { 3 private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); 4 5 private const string DATABASE_NAME = "moneyfox3.db"; 6 7 public static string GetDbPath() 8 { 9 string databasePath = ""; 10 switch (ExecutingPlatform.Current) 11 { 12 case AppPlatform.iOS: 13 SQLitePCL.Batteries_V2.Init(); 14 databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library", DATABASE_NAME); 15 break; 16 case AppPlatform.Android: 17 databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), DATABASE_NAME); 18 break; 19 20 case AppPlatform.UWP: 21 databasePath = DATABASE_NAME; 22 break; 23 24 default: 25 throw new NotSupportedException("Platform not supported"); 26 } 27 28 Logger.Debug(CultureInfo.CurrentCulture, "Database Path: {dbPath}", databasePath); 29 return databasePath; 30 } 31 }
下面是该方式的使用效果
https://docs.microsoft.com/zh-cn/ef/core/miscellaneous/configuring-dbcontext
https://www.cnblogs.com/CreateMyself/p/6224141.html
1 public void ConfigureServices(IServiceCollection services) 2 { 3 services.AddMvc(); 4 var connection = Configuration 5 .GetConnectionString("DefaultConnection"); 6 services.AddDbContext<CRMContext>( 7 options => options.UseSqlServer(connection, 8 //MigrationsAssembly 配置为该上下文维护迁移的程序集。 9 b => b.MigrationsAssembly("DataLayer"))); 10 }