1.外部传入
public partial class App : Application
{
ServiceProvider serviceProvider { get; set; }
protected override void OnStartup(StartupEventArgs e)
{
var service=new ServiceCollection();
ConfigurationService(service);
serviceProvider = service.BuildServiceProvider();
var mainView = serviceProvider.GetRequiredService<MainWindow>();
mainView.Show();
base.OnStartup(e);
}
private void ConfigurationService(ServiceCollection service)
{
service.AddTransient(typeof(MainWindow));
//service.AddDbContext<SchemeContext>();
IConfiguration configuration;
var builder = new ConfigurationBuilder();
builder.AddJsonFile(System.Environment.CurrentDirectory+"\\AppSetting.json", false, true);
configuration = builder.Build();
var value=configuration.GetSection("Oracle");
if(value == null)
{
MessageBox.Show("请配置数据库连接");
Application.Current.Shutdown();
}
service.AddDbContext<SchemeContext>(option => { option.UseOracle(value.Value, f => f.UseOracleSQLCompatibility("12")); });
}
}
- 在数据库上下文中OnConfiguring方法中构造
public class SchemeContext : DbContext
{
public SchemeContext(DbContextOptions options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseOracle("Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.2.48)(PORT = 1521)))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = CASICTEST)));User ID=mes;Password=mesadmin;", f => f.UseOracleSQLCompatibility("12"));
}
}