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

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.

主站蜘蛛池模板: 凤山市| 临澧县| 同仁县| 台东县| 禹州市| 东乡族自治县| 温宿县| 白城市| 宿州市| 湘潭市| 徐闻县| 边坝县| 福海县| 津南区| 集贤县| 清丰县| 咸丰县| 博白县| 乌恰县| 大理市| 盈江县| 衡阳县| 乌海市| 泗水县| 安义县| 巴彦县| 峨边| 福泉市| 上思县| 百色市| 赞皇县| 兰考县| 满城县| 兴业县| 黎城县| 来宾市| 延吉市| 徐闻县| 上犹县| 桂平市| 油尖旺区|