- 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.
推薦閱讀
- JBoss Weld CDI for Java Platform
- 深入理解Bootstrap
- C/C++算法從菜鳥到達人
- Programming ArcGIS 10.1 with Python Cookbook
- 青少年美育趣味課堂:XMind思維導圖制作
- Python爬蟲開發與項目實戰
- 可解釋機器學習:模型、方法與實踐
- Getting Started with Hazelcast(Second Edition)
- Mastering openFrameworks:Creative Coding Demystified
- Java零基礎實戰
- iOS開發項目化入門教程
- 超好玩的Scratch 3.5少兒編程
- Google Adsense優化實戰
- Android應用開發攻略
- Scala編程(第4版)