021 Modify DBContext for the second entity (Enterprise) - chempkovsky/CS82ANGULAR GitHub Wiki

Using DBContext Wizard is absolutely necessary

Steps required to accomplish the task

Run DBContext Wizard
  • repeat the steps described in the article
First page of DBContext Wizard
  • repeat the steps described in the article
Second page of DBContext Wizard
  • repeat the steps described in the article
Sixth page of DBContext Wizard

On the Sixth page of the Wizard choose PhBkEntity.csproj and PhbkEnterprise-class and click Add Required property to Db-context-button

Click to show the picture

project structure

It will add the following lines of code to the PhbkDbContext.cs file.

        public DbSet<PhbkEnterprise> PhbkEnterpriseDbSet {
            get => Set<PhbkEnterprise>();
            
        }

In addition the content of the second page of the Wizard has changed. Now it shows the message about the primary Key of the entity. Click Modify-button. (It will show Primary Key page of DBContext Wizard.)

Click to show the picture

project structure

Primary Key page of DBContext Wizard
  • On the Primary Key page
    • choose EntrprsId-property to be used as a primary key,
    • choose HasKey.Net.Core.cs.t4-script to generate the code
    • click Create(modify)-button
Click to show the picture

project structure

It modifies OnModelCreating-method of the DbContext class as shown below:

Click to show the code
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
             ...
             modelBuilder.Entity<PhbkEnterprise>().HasKey(p => p.EntrprsId);
             ...
        }

Click Next-button to navigate to Unique Key page of DBContext Wizard

Unique Key page of DBContext Wizard
  • On the Primary Key page
    • enter EntrprsNameUK as a unique key name. The Unique key name is a required property. It is used by the generator scripts.
    • choose EntrprsName-property to be used as a Unique key,
    • choose HasAlternateKey.Net.Core.cs.t4-script to generate the code
    • click Create(modify)-button
Click to show the picture

project structure

It modifies OnModelCreating-method of the DbContext class as shown below:

Click to show the code
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
             ...
             modelBuilder.Entity<PhbkEnterprise>().HasAlternateKey(p => p.EntrprsName).HasName("EntrprsNameUK");
             ...
        }
Second page of DBContext Wizard second time

Click Cancel-button to close DBContext Wizard

Click to show the picture

project structure

⚠️ **GitHub.com Fallback** ⚠️