- 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.
推薦閱讀
- PHP動態網站程序設計
- Java逍遙游記
- PostgreSQL Cookbook
- iOS開發實戰:從零基礎到App Store上架
- Mastering AndEngine Game Development
- Java設計模式及實踐
- PhoneGap:Beginner's Guide(Third Edition)
- Angular開發入門與實戰
- Windows Embedded CE 6.0程序設計實戰
- Hands-On Full Stack Development with Spring Boot 2.0 and React
- Oracle Data Guard 11gR2 Administration Beginner's Guide
- Python第三方庫開發應用實戰
- Android智能手機APP界面設計實戰教程
- Laravel Design Patterns and Best Practices
- Building Apple Watch Projects