im having some problems with EF 5 when i want to map many to many relationships using code first. This is my scenario:
public class SegFunction
{
public virtual string Idaplication {get;set;}
public virtual string Idfunction {get;set;}
public virtual List<SegRole> Roles { get; set; }
}
public class SegRole
{
public virtual int Idrole { get; set; }
public virtual List<SegFunction> Functions { get; set; }
}
This are my maps:
private void MapSegRole()
{
this.modelBuilder.Entity<SegRole>()
.Map(entity =>
{
entity.ToTable("seg_roles");
});
this.modelBuilder.Entity<SegRole>()
.Property(t => t.Idrole).HasColumnName("id_role");
this.modelBuilder.Entity<SegRole>()
.HasKey(c => c.Idrole);
modelBuilder.Entity<SegRol>()
.HasMany(i => i.Functions)
.WithMany(c => c.Roles)
.Map(
m =>
{
mc.ToTable("seg_role_function");
m.MapRightKey("id_role");
m.MapLeftKey("id_aplication");
m.MapLeftKey("id_function");
});
}
And
private void MapSegFunction()
{
this.modelBuilder.Entity<Segfunction>()
.Map(entity =>
{
entity.ToTable("seg_functions");
});
this.modelBuilder.Entity<Segfunction>()
.Property(t => t.Idfunction).HasColumnName("id_function");
this.modelBuilder.Entity<Segfunction>()
.Property(t => t.Idaplication).HasColumnName("id_aplication");
this.modelBuilder.Entity<Segfuncion>()
.HasKey( d => new { d.Idaplication, d.Idfunction});
this.modelBuilder.Entity<Segfunction>()
.HasMany(t => t.Roles)
.WithMany(r => r.Functions)
.Map(mc =>
{
mc.ToTable("seg_role_function");
mc.MapLeftKey("id_role");
mc.MapRightKey("id_aplication");
mc.MapRightKey("id_function");
});
}
I have three tables Seg_Role, Seg_Function, Seg_role_function where seg_function has composite primary key (id_aplication, id_function) and seg_role_function has a composite key (id_role, id_aplication, id_function)
i'm getting the following error when i try to get from context:
The specified association foreign key columns 'id_role' are invalid. The number of columns specified must match the number of primary key columns.