EntityFramework从表中检索信息

时间:2014-02-01 18:42:18

标签: c# entity-framework

我的dbContext

中有一个ManyToMany关系
modelBuilder.Entity<Role>().HasMany(r => r.Permissions).WithMany(p => p.Roles)
                .Map(
                    m =>
                    {
                        m.MapLeftKey("role_id");
                        m.MapRightKey("per_id");
                        m.ToTable("roles_permissions");
                    }
                );

Role.cs看起来像:

public class Role
{
    [Key]
    public int role_Id { get; set; }
    public string Name { get; set; }
    public ICollection<LoginModel> Users { get; set; }

    public ICollection<Permission> Permissions { get; set; }

    public Role()
    {
        Users = new List<LoginModel>();
        Permissions = new Collection<Permission>();

    }
}

和Permission.cs看起来像:

public class Permission
{
    [Key]
    public int permi_Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Role> Roles { get; set; }

    public Permission()
    {
        Roles = new Collection<Role>();
    }
}

我想从特定角色获取列表中的所有权限...我正在尝试使用此

var role = from a in db.Roles
           where a.Name.Equals(txt_modificar_nombre.Text)
           select a.Permissions;

role不允许我获得权限,因为var role的类型为:enter image description here

有人可以帮助我吗?

这些是我想要打印的值......

var role

的断点值

enter image description here

1 个答案:

答案 0 :(得分:1)

您将每个匹配的角色投射到权限序列中。因此,您有查询返回序列序列。你需要压扁结果:

var permissions = from r in db.Roles
                  where r.Name == txt_modificar_nombre.Text
                  from p in r.Permissions
                  select p;

在lambda语法中,有单独的运算符SelectMany用于投影和展平:

var permissions = db.Roles.Where(r => r.Name == txt_modificar_nombre.Text)
                          .SelectMany(r => r.Permissions);