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

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.

主站蜘蛛池模板: 方正县| 怀集县| 仁寿县| 临城县| 苏尼特左旗| 灌南县| 和顺县| 观塘区| 蓝山县| 肥乡县| 安陆市| 西吉县| 高安市| 明星| 得荣县| 克什克腾旗| 资溪县| 瓮安县| 南和县| 泊头市| 喀喇沁旗| 安图县| 调兵山市| 新郑市| 镇巴县| 庆城县| 清水县| 肥乡县| 高平市| 磐安县| 会同县| 花莲县| 五指山市| 清水县| 江津市| 茌平县| 嘉祥县| 镇宁| 南郑县| 垦利县| 清水县|