- 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.
推薦閱讀
- Mastering Zabbix(Second Edition)
- Mastering RabbitMQ
- 算法基礎:打開程序設計之門
- Internet of Things with the Arduino Yún
- Easy Web Development with WaveMaker
- Yocto for Raspberry Pi
- Python忍者秘籍
- MATLAB GUI純代碼編寫從入門到實戰
- 算法圖解
- INSTANT Apache ServiceMix How-to
- 零基礎學Java(第5版)
- 邊做邊學深度強化學習:PyTorch程序設計實踐
- React Router Quick Start Guide
- 區塊鏈社會:區塊鏈助力國家治理能力現代化
- Java面向對象程序設計(第3版)