当我想首先使用代码映射多对多关系时,我遇到了 EF 5 的一些问题。这是我的场景:
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; }
}
这是我的地图:
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");
});
}
和
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");
});
}
我有三个表 Seg_Role、Seg_Function、Seg_role_function,其中 seg_function 具有复合主键(id_aplication、id_function),而 seg_role_function 具有复合键(id_role、id_aplication、id_function)
当我尝试从上下文中获取时出现以下错误:
指定的关联外键列“id_role”无效。指定的列数必须与主键列数匹配。