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

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.

主站蜘蛛池模板: 通海县| 绿春县| 秭归县| 肥城市| 老河口市| 平和县| 太仆寺旗| SHOW| 河源市| 伊川县| 澎湖县| 霞浦县| 定陶县| 毕节市| 图木舒克市| 原阳县| 廉江市| 紫阳县| 吴桥县| 湖北省| 乌兰察布市| 泸州市| 阜南县| 通化县| 榆中县| 鹤庆县| 杨浦区| 南平市| 浪卡子县| 鹿泉市| 桐城市| 临桂县| 额尔古纳市| 山东省| 百色市| 正定县| 伊吾县| 大城县| 拉孜县| 舒兰市| 洛浦县|