查询以从多个表中获取信息

时间:2015-07-06 12:38:30

标签: sql-server wpf linq entity-framework join

我的数据库中有以下标签

  1. TestPack {id,name,type}
  2. InternalWalk {id,tp_id,date}
  3. ExternalWalk {id,tp_id,date}
  4. 刷新{id,tp_id,date}
  5. PunchItems {id,tp_id,name,type,category,reporteddate,closedDate}
  6. tp_Id是TestPack id,是所有其他表中的外键,这意味着TestPack可能具有1-N内部/外部步行,Flushings和PunchItems。

    现在我想查询数据库(使用EF LINQ)以返回测试包,以及针对一个测试包的所有Walks,Flushings,Punchitems,以便我可以在单个DataGrid中显示所有这些信息?

    测试包,没有任何Flushings,Walks,PunchItems不应出现在结果中。如果存在任何一个,则应在结果中显示测试包

    编辑:

     var queryResult = 
                                from tp in allTestPacks
                                join iwalk in allInternalWalks on tp.id equals iwalk.test_pack_id.Value 
                                into tpIwalk from iwalk in tpIwalk.DefaultIfEmpty()
    
                                join ewalk in allExternalWalks on tp.id equals ewalk.test_pack_id.Value
                                into tpEwalk from ewalk in tpEwalk.DefaultIfEmpty()
    
                                join flings in allFlushings on tp.id equals flings.test_pack_id.Value
                                into tpFlings from flings in tpFlings.DefaultIfEmpty()
    
                                join pitems in allPunchItems on tp.id equals pitems.test_pack_id.Value
                                into tpPitems from pitems in tpPitems.DefaultIfEmpty()
                                select new
                                {
                                    TestPackID = tp.test_pack_no,
                                    InternalWalkdDate = iwalk != null ? iwalk.RFIDate : null,
                                    ExternalWalkDate = ewalk != null ? ewalk.RFIDate : null,
                                    FlushinDate = flings != null ? flings.rfi_no : null,
                                    PunchItemCategory = pitems != null ? pitems.description : null//etc
                                };
    

1 个答案:

答案 0 :(得分:0)

编辑:整理不必要的通行证

var resultset = from tp in allTestPacks
 join iwalk in allInternalWalks on tp.id equals iwalk.test_pack_id.Value into tpIwalk 
 join ewalk in allExternalWalks on tp.id equals ewalk.test_pack_id.Value  into tpEwalk 
 join flings in allFlushings on tp.id equals flings.test_pack_id.Value into tpFlings
 join pitems in allPunchItems on tp.id equals pitems.test_pack_id.Value into tpPitems 

 from iwalk in tpIwalk.DefaultIfEmpty()
 from ewalk in tpEwalk.DefaultIfEmpty()
 from flings in tpFlings.DefaultIfEmpty()
 from pitems in tpPitems.DefaultIfEmpty()

select new
{
 TestPackID = tp.test_pack_no,
 InternalWalkdDate = iwalk != null ? iwalk.RFIDate : null,
 ExternalWalkDate = ewalk != null ? ewalk.RFIDate : null,
 FlushinDate = flings != null ? flings.rfi_no : null,
 PunchItemCategory = pitems != null ? pitems.description : null//etc
};

Console.WriteLine ((System.Data.Objects.ObjectQuery) resultset).ToTraceString();