Search code examples
c#entity-frameworkfluent

Many to Many relationship EF with foreign keys


I want to configure many to many relationship between 2 entities but I would also like to expose their foreign keys. I found only one concrete solution online like following:

modelBuilder.Entity<E1>()
                            .HasMany(t => t.E1s)
                            .WithMany(t => t.E2s)
                            .Map(m =>
                            {
                                m.ToTable("E1E2");
                                m.MapLeftKey("FKE1");
                                m.MapRightKey("FKE2");
                            });

But map left and right key does not take a properties from my models so I do not have access to them and they will not be filled when I query. So, I do not have access to my foreign key properties.

Hope I was able to explain my problem. Can anyone suggest any other option?


Solution

  • You can create an associative model that has keys from the two entities:

    public class AssociativeEntity
    {
        [Key]
        public Guid AssociativeEntityId { get; set; }
        public Guid Entity1Id { get; set; }
        public Guid Entity2Id { get; set; }
    
        [Display(Name = "Entity1", ResourceType = typeof(Resources.Language))]
        public virtual Entity1 Entity1 { get; set; }
        [Display(Name = "Entity2", ResourceType = typeof(Resources.Language))]
        public virtual Entity2 Entity2 { get; set; }
    }
    

    Entity 1:

    public class Entity1
    {
        [Key]
        public Guid Entity1Id { get; set; }
    
        /* Describe the other properties here */
    
        [Display(Name = "AssociativeEntities", ResourceType = typeof(Resources.Language))]
        public virtual ICollection<AssociativeEntity> AssociativeEntities { get; set; }
    }
    

    Entity 2:

    public class Entity2
    {
        [Key]
        public Guid Entity2Id { get; set; }
    
        /* Describe the other properties here */
    
        [Display(Name = "AssociativeEntities", ResourceType = typeof(Resources.Language))]
        public virtual ICollection<AssociativeEntity> AssociativeEntities { get; set; }
    }