Cover image for EF Builder Entity One to Many Configuration

EF Builder Entity One to Many Configuration

jwp profile image John Peters Updated on ・2 min read
             .HasOne(e => e.SettingGroup)
             .WithMany(fe => fe.Settings);
              .HasMany(p => p.Options)
              .HasForeignKey(p => p.SettingID);
              .HasMany(p => p.CurrentValueList)
              .WithOne().HasForeignKey(p => p.SettingID);

EF is not without a bit of extra work, as we must (when using code-first) configure all the DB Relationships.

We have a class named Setting which looks like this:

    public class Setting

        public int ID { get; set; }
        public string DisplayName { get; set; }
        public string Description { get; set; }
        public string Owner { get; set; }
        public string Size { get; set; }
        public string Type { get; set; } 
        public int SettingGroupID { get; set; }
        public virtual SettingsGroup SettingGroup { get; set; }
        public virtual List<SettingOption> Options { get; set; } = new List<SettingOption>();
        public virtual List<SettingValue> CurrentValueList { get; set; } = new List<SettingValue>();

The first EF rule is that all the default properties will be automatically generated at Update Database time based on a Migration (No special configurations are needed for them). Migrations are a way for all the changes to be cataloged. If needed, changes can be rolled back (however we don't use that feature as we aren't in production yet).

Virtual Properties

All Virtual Properties indicate what is known as a navigation property; therefore, this line of code:

             .HasOne(e => e.SettingGroup)
             .WithMany(fe => fe.Settings);

Is telling EF that the database relationship with the class "Setting" Has one "SettingGroup" which contains multiple "Settings". Indeed the class SettingsGroup has mulitple settings in it as shown below.

    public class SettingsGroup
        public int ID { get; set; }
        public string UserName {get;set;}
        public string DisplayName { get; set; }
        public virtual List<Setting> Settings { get; set; }      

Notice that the "Settings" property above is virtual. This is a requirement for anything such as a list, or anything needing a Foreign Key relationship.

Once the database update is run, we see this in the "Settings" field named "SettingsControls".

Alt Text

Notice the PK and FK designations within the parenthesis.

This shows how to get your database's impedance mismatch synced with class objects within your project. Be patient when first learning this because it is a bit odd and confusing... Just keep plugging away and ask for help if you need it.


Posted on Mar 31 by:

jwp profile

John Peters


Angular, React, Typescript and JavaScript. The wave of now!


markdown guide