30 Modify DBContext for the entity (Country) (Wpf, Xamarin) - chempkovsky/CS2WPF-and-CS2XAMARIN GitHub Wiki
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.
- Step #1:
- Right Click “Literature” of the “Dm02Context”-project and Select “DBContext Wizard” menu item to open the Wizard dialog
- 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.
- Click “Next”
- Step #3:
- On the third page select “Dm01Entity”-project and “LitCountry”-entity.
- Click “Add required property to DbContext”
- `DbSet<LitCountry>`
- 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.
- Click “Modify”
- Step #5:
- Add ”Iso3” and "Iso2" to the primary key list. The order is important!
- Select “HasKey.Net.cs.t4” template
- Click “Create(Modify)” button. It will add Fluent Api definition of the primary key for “LitCountry”.
modelBuilder.Entity<LitCountry>().HasKey(p => new { p.Iso3, p.Iso2 });
- Step #6 (Optional):
- Open “LitDbContext.cs” file
- Find the constructor and change as follows:
public LitDbContext() : base("name=LitConnection") { }