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

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.

主站蜘蛛池模板: 平原县| 日照市| 大兴区| 惠来县| 临夏市| 大安市| 淮南市| 闻喜县| 乌拉特前旗| 鄱阳县| 富裕县| 临泉县| 林州市| 屏南县| 顺义区| 改则县| 西林县| 屏南县| 房产| 吐鲁番市| 康乐县| 建阳市| 高碑店市| 晋州市| 岳阳市| 黄骅市| 金川县| 阳山县| 碌曲县| 兴文县| 兰溪市| 中方县| 贵南县| 汉沽区| 冷水江市| 吐鲁番市| 曲阜市| 屯留县| 龙泉市| 高密市| 沙洋县|