- Mastering Entity Framework Core 2.0
- Prabhakaran Anbazhagan
- 154字
- 2021-07-02 21:16:40
Refactoring the OnConfiguring() method
If we recap on how we have configured the database context, the auto-generated code had a hardcoded connection string used for configuration. To avoid it, we should have a mechanism to pass on the database context options to the DbContext base class; let's see how to do it:
public partial class MasteringEFCoreDbFirstContext : DbContext
{
public virtual DbSet<Blog> Blog { get; set; }
public virtual DbSet<Post> Post { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder
optionsBuilder)
{
// Move this connection string to config file later
optionsBuilder.UseSqlServer(@"Server=
(localdb)\mssqllocaldb;Database=MasteringEFCoreDbFirst;
Trusted_Connection=True;");
}
}
Also include a constructor for the MasteringEFCoreDbFirstContext class, which will initialize the DbContext through dependency injection from the Startup class:
public
MasteringEFCoreDbFirstContext(
DbContextOptions<MasteringEFCoreDbFirstContext> options)
: base(options)
{
}
We have seen how to pass on the options to the database context base class, now we will see how the options were configured with a connection string.
推薦閱讀
- Boost程序庫完全開發(fā)指南:深入C++”準”標準庫(第5版)
- 深度實踐OpenStack:基于Python的OpenStack組件開發(fā)
- Java高手真經(jīng)(高級編程卷):Java Web高級開發(fā)技術(shù)
- Oracle 12c中文版數(shù)據(jù)庫管理、應用與開發(fā)實踐教程 (清華電腦學堂)
- jQuery從入門到精通 (軟件開發(fā)視頻大講堂)
- Apache Mesos Essentials
- 軟件測試教程
- Kotlin極簡教程
- Extending Unity with Editor Scripting
- C語言程序設(shè)計實踐
- Implementing Microsoft Dynamics NAV(Third Edition)
- Java 11 and 12:New Features
- JavaScript語法簡明手冊
- Cloud Development andDeployment with CloudBees
- Mastering VMware vSphere Storage