- 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.
推薦閱讀
- Implementing VMware Horizon 7(Second Edition)
- Oracle 11g從入門到精通(第2版) (軟件開發視頻大講堂)
- C語言程序設計(第3版)
- Python自動化運維快速入門(第2版)
- Mastering C# Concurrency
- Access 2010數據庫基礎與應用項目式教程(第3版)
- 移動界面(Web/App)Photoshop UI設計十全大補
- 低代碼平臺開發實踐:基于React
- 硅谷Python工程師面試指南:數據結構、算法與系統設計
- PySpark Cookbook
- Spring Boot+Vue全棧開發實戰
- 零代碼實戰:企業級應用搭建與案例詳解
- Python Programming for Arduino
- Penetration Testing with the Bash shell
- 可視化H5頁面設計與制作:Mugeda標準教程