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

Configuring data context

The auto-generated database context (which is presented in the following code) will include:

  • Virtual properties of the tables/entities to hold corresponding data.
  • The OnConfiguring method, which will configure EF with the database.
  • The OnModelCreating method, which will ensure certain constraints and relationships are built while creating the database. It would not be used in our database-first approach as we already have them in place.

The database context should contain the following configuration:

    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)
{
if (!optionsBuilder.IsConfigured)
{
// Move this connection string to config file later
ptionsBuilder.UseSqlServer(@"Server=
(localdb)\mssqllocaldb;Database=MasteringEFCoreDbFirst;
Trusted_Connection=True;");
}
}
protected override void OnModelCreating(ModelBuilder
modelBuilder)
{
modelBuilder.Entity<Post>(entity =>
{
entity.HasIndex(e => e.BlogId).HasName("IX_Post_BlogId");
entity.Property(e => e.Title).IsRequired();
entity.HasOne(d => d.Blog).WithMany(p => p.Post)
.HasForeignKey(d => d.BlogId);
});
}
}

In case you have noticed the warning, we need to remove the section using dependency injection, which will be performed in the Registering Context in Services (.NET Core DI) section.

主站蜘蛛池模板: 云和县| 尤溪县| 高要市| 普兰店市| 武定县| 中超| 南和县| 津南区| 永清县| 原平市| 新乐市| 裕民县| 湾仔区| 凤冈县| 弥勒县| 竹溪县| 无为县| 新巴尔虎左旗| 连平县| 攀枝花市| 仁寿县| 会同县| 东阿县| 兴和县| 长寿区| 扬中市| 绥阳县| 澳门| 四平市| 四平市| 新宁县| 广宗县| 彭州市| 界首市| 靖远县| 信阳市| 吉木萨尔县| 肇东市| 呈贡县| 潼南县| 鄯善县|