官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 夹江县| 通化县| 萝北县| 巴楚县| 阳高县| 定远县| 宣威市| 中西区| SHOW| 伊金霍洛旗| 陇西县| 五家渠市| 龙胜| 舟曲县| 八宿县| 盈江县| 陆良县| 茂名市| 岑巩县| 永川市| 通山县| 白水县| 双江| 荥经县| 揭东县| 常德市| 周宁县| 吉木乃县| 延边| 东兰县| 广平县| 龙山县| 五大连池市| 林口县| 通江县| 邯郸县| 汽车| 醴陵市| 潞西市| 卓资县| 息烽县|