使用Entity框架处理Linq中的一对多关系

时间:2012-01-24 15:27:30

标签: c# linq entity-framework-4.1

我有一个名为Direccion的表,其他名为Cliente,每个都像这样定义

public class Direccion
{   
    public short IdDireccion { get; set; }
    public short IdCliente { get; set; }
    public string Descripcion{ get; set; }
    public virtual ICollection<Cliente> Cliente { get; set; }
}

public class Cliente
{
    public short IdCliente { get; set; }
    public string Descripcion { get; set; }
}

现在我想要完成的是通过生成匿名类型

来查询此输出
id            <----could be idCliente or idDireccion
Descripcion   <----could be the description of cliente or Direccion
idFK          <---- the id of direccion related with cliente

但是当我从Direccion导航到Cliente时,我开始遇到麻烦,因为这个关系给了我收藏,我不知道如何使表达式处理集合到那个类型我期待哪个是Cliente

这是我失败的尝试:

var x= (from d in Direccion
where d.Activo == true select d.Cliente).Select( x => new { x.IdCliente })

var x = (from d in db.Direccion
                     where d.Activo == true
                     select d).AsQueryable().Select(xx => new { d.IdCliente });

1 个答案:

答案 0 :(得分:3)

尝试使用SelectMany方法:

var x = from d in db.Direccion
        where d.Activo == true
        from c in d.Cliente
        select new 
        { c.IdCliente,
          c.Descripcion };