22 Modify DBContext for the entity (Edition) (Wpf, Xamarin) - chempkovsky/CS2WPF-and-CS2XAMARIN GitHub Wiki

Using “DBContext Wizard” is absolutely necessary

The DBContext Wizard is a tool that creates or modifies an existing DBContext file. There are a lot of such tools. And the question is, "why was it created."

  • The answer is as follows:
    • Other wizards (ModelViews, WebApiServices) parse the DBContext file and Entities files for their own needs. But the task of creating full-feature parser is a time consuming. On the other hand, only a few fluent api constructs are used by ModelViews, WebApiServices wizards. So, instead of creating a fully functional parser, I created a small code generator for a very short list of constructs. According to (https://www.entityframeworktutorial.net/efcore/configure-one-to-many-relationship-using-fluent-api-in-ef-core.aspx) some fluent api designs can be done in more than one way. To make sure that the ModelViews and WebApiServices wizards parse the fluent api structures correctly, a DBContext Wizard was developed. So, using DBContext Wizard is absolutely necessary. It generates fluent api constructs in a way that ModelViews and WebApiServices wizards parse correctly.

Steps required to accomplish the task

  • Step #1:
    • Right Click “Literature” of the “Dm02Context”-project and Select “DBContext Wizard” menu item to open the Wizard dialog

picture

- Note:
    - On the first page of the dialog the destination folder is shown. The destination folder is the folder in which the generated file will be created.
    - Click “Next”-button
  • Step #2:
    • The developer is on the second page. Now select the "Dm02Context" project and the "LitDbContext" context that has already been created.

picture

- Click “Next” 
  • Step #3:
    • On the third page select “Dm01Entity”-project and “LitEdition”-entity.

picture

- Click “Add required property to DbContext”
    - `DbSet<LitEdition>`
- property will be added to the context
  • Step #4:
    • On the same third page, the “Modify”-button became available.
    • The developer must explicitly define the primary key.

picture

- Click “Modify”
  • Step #5:
    • Add ”EditionId” to the primary key list.
    • Select “HasKey.Net.cs.t4” template
    • Click “Create(Modify)” button. It will add Fluent Api definition of the primary key for “LitEdition”.

picture

    modelBuilder.Entity<LitEdition>().HasKey(p => p.EditionId);
  • Step #6 (Optional):
    • Open “LitDbContext.cs” file
    • Find the constructor and change as follows:
        public LitDbContext()
          : base("name=LitConnection")
        {
        }
⚠️ **GitHub.com Fallback** ⚠️