Entity Framework 6 - Multiple Many-to-manu with Fluent Api

12 views Asked by At

I had implemented Fluent API using Entity Framework 6.

Tables are: enter image description here

Funzione class:

   [Key]
   [StringLength(10)]
   [Column(Order = 0)]
   public string ID { get; set; }

   [Key]
   [Column(Order = 1)]
   public int TenantId { get; set; }

   [Required]
   [StringLength(255)]
   public string Description { get; set; }

   public virtual ICollection<ApplicationUser> ApplicationUsers { get; set; }
   public virtual ICollection<ApplicationRole> ApplicationRoles { get; set; } 

Users class:

    [Key]
    public int Id { get; set; }
    public string Email { get; set; }
    public string UserName { get; set; }
   
    public virtual ICollection<Funzione> Funzioni { get; set; }

Roles class:

    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int TenantId { get; set; }
           
    public virtual ICollection<Funzione> Funzioni { get; set; }

Builder:

  modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");
  modelBuilder.Entity<ApplicationRole>().ToTable("AspNetRoles");
  modelBuilder.Entity<Funzione>().ToTable("Wpl_Funzioni");

  modelBuilder.Entity<Funzione>()
      .HasMany(f =>  f.ApplicationUsers)
      .WithMany(f => f.Funzioni)
      .Map(m =>
            {
                m.MapLeftKey(new[] { "IDFunzione", "TenantId" });
                m.MapRightKey("IDUtente");
                m.ToTable("Wpl_DestinatariFunzione");
            });

With previous code all is fine, the user has the functions belong to.

But if I add the code below for roles:

modelBuilder.Entity<Funzione>()
  .HasMany(f => f.ApplicationRoles)
  .WithMany(f => f.Funzioni)
  .Map(m =>
     {
        m.MapLeftKey(new[] { "IDFunzione", "TenantId" });
        m.MapRightKey("IDGruppoUtenti");
        m.ToTable("Wpl_DestinatariFunzione");
     });

applicatione return this error:

"The EntitySet 'FunzioneApplicationUser' with schema 'dbo' and table 'Wpl_DestinatariFunzione' was already defined. Each EntitySet must refer to a unique schema and table"

I need to have also that role has the functions belong to. Could somebody tell me how to achieve this using Fluent API?

0

There are 0 answers