使用Entity框架处理Linq中的一对多关系
本文关键字:一对多 关系 Linq Entity 框架 处理 使用 | 更新日期: 2023-09-27 18:21:20
我有一个表叫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 });
尝试SelectMany方法:
var x = from d in db.Direccion
where d.Activo == true
from c in d.Cliente
select new
{ c.IdCliente,
c.Descripcion };