- Mastering Entity Framework Core 2.0
- Prabhakaran Anbazhagan
- 182字
- 2021-07-02 21:16:40
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.
推薦閱讀
- Web程序設計及應用
- Modular Programming with Python
- Java程序設計實戰教程
- Redis Applied Design Patterns
- Software Testing using Visual Studio 2012
- oreilly精品圖書:軟件開發者路線圖叢書(共8冊)
- React.js Essentials
- 量化金融R語言高級教程
- 零基礎學Python網絡爬蟲案例實戰全流程詳解(入門與提高篇)
- 運用后端技術處理業務邏輯(藍橋杯軟件大賽培訓教材-Java方向)
- Internet of Things with ESP8266
- 程序員的成長課
- Functional Python Programming
- JavaWeb從入門到精通(視頻實戰版)
- C++標準庫(第2版)