locked
Linq查询一对多关系,怎么取值 RRS feed

  • 问题

  • 订单表,一个订单里有多个乘客,乘客在乘客表存储。

    取一条订单时,把关联的乘客也都取出来。

    但是绑定时怎么显示乘客的某个属性,比如乘客的姓名,乘客的证件等?


    开心了就笑,不开心了就过会儿再笑

    2015年2月7日 6:07

答案


  • Hello,

    请问你的数据量大吗?如果不是很大的话,你可以用LINQ2Object:

    using (DFDBEntities db = new DFDBEntities())
    
                    {
    
                        var result = db.Orders.ToList().Select(o => new { OID = o.OrderID, ODNames = string.Join(",", o.OrderDetails.Select(od => od.OrderDetailName)) }).ToList();
    
                    }
    

    这种方式会把数据记录预先加载到内存中然后对内存中的数据库进行删选,这里主要用了string.Join这个函数,这个在Linq2Enities是不能被识别的。

    或这用嵌套循环:

    Foreach()//对父表循环
    
    {
    
                    Foreach()//对子表循环
    
                    {
    
                    
    
    }
    
    }
    

    这个会多写点代码。

    Regards.

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    2015年2月9日 2:48
    版主

全部回复

  • var q=from o in db.Orders where ordno='xxxx'
    select new{
       o.ordno,
       o.status,
       passengers=(from p in db.passengers where p.ordno==o.ordno select new{p.name,p.card})
    };

    绑定的时候,乘客列 把乘客的名字都显示出来,然后逗号间隔,不知道怎么弄了,求大神指教

    开心了就笑,不开心了就过会儿再笑

    2015年2月7日 6:17

  • Hello,

    请问你的数据量大吗?如果不是很大的话,你可以用LINQ2Object:

    using (DFDBEntities db = new DFDBEntities())
    
                    {
    
                        var result = db.Orders.ToList().Select(o => new { OID = o.OrderID, ODNames = string.Join(",", o.OrderDetails.Select(od => od.OrderDetailName)) }).ToList();
    
                    }
    

    这种方式会把数据记录预先加载到内存中然后对内存中的数据库进行删选,这里主要用了string.Join这个函数,这个在Linq2Enities是不能被识别的。

    或这用嵌套循环:

    Foreach()//对父表循环
    
    {
    
                    Foreach()//对子表循环
    
                    {
    
                    
    
    }
    
    }
    

    这个会多写点代码。

    Regards.

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    2015年2月9日 2:48
    版主