Search code examples
sqlentity-frameworkdbcontextfluentef-fluent-api

Fluent API One to Many relation with static table


I need help. I have three static table (Dictionary of Country, Region and Cities). I set this tables in my Initilizer class. I need to create One to Many relation with my own User table without created Foregion Key in dictionaries tables by Fluent API.

Dictionary Tables (Countries, Regions and Cities):

enter image description here

My User table:

public class UserWorker
{
  public UserWorker()
    {
        Countries = new List<DCountry>();
        Regions = new List<DRegion>();
        Cities = new List<DCity>();
        Professions = new List<DProfession>();
    }

    public int UserWorkerId { get; set; }

    public virtual ICollection<DCountry> Countries { get; set; }

    public virtual ICollection<DRegion> Regions { get; set; }

    public virtual ICollection<DCity> Cities { get; set; }

    public virtual ICollection<DProfession> Professions { get; set; }
}

How I can add relation without UserWorker_UserWorkerId ?

P.S: I have another two my own table that need to connect by the same relation One to Many by Fluent API.

I don't understand how i can add Objects dictionary lists to my own table without create virtual foregion key in my static table.


Solution

  • If a single user can have many cities, and the same city can be assigned to many users, this is a many-to-many relationship.

    You can configure this in the ModelBuilder as follows:

    ModelBuilder.Entity<UserWorker>()
       .HasMany(u => u.Cities)
       .WithMany()
       .Map(x => {
            x.MapLeftKey("UserWorkerId");
            x.MapRightKey("CityId");
            x.ToTable("UserWorkerToCityMap");
       });
    

    EF will create an additional table UserWorkerToCityMap for this relationship that has two columns with foreign key references to UserWorkerId and CityId. No additional foreign key column will be added to DCity.

    Configure Many-to-Many Relationship in Code-First