2012-05-23 46 views
1

我目前有以下linq,它運行並獲取兩個強類型對象(DAL.Driver和DAL.Licence)。但是我想將結果轉換爲包含BLL.Driver和BLL.Licence對象的單個DriverODSJoined對象。Linq查詢結果到兩個對象中

public class DriverODSJoined 
{ 
    public BLL.Driver driver { get; set; } 
    public BLL.Licence licence { get; set; } 

    public static void GetData() 
    { 
     DAL.DriverDataContext dataContext = new DAL.DriverDataContext(); 

     var query = (from d in dataContext.drivers 
        join c in dataContext.licences on d.licence_id equals c.id into t1 
        from t2 in t1.DefaultIfEmpty() 
        select new { Driver = d, Licence = t2 }); 
    } 
} 

對於鏈接查詢到一個類的對象,我會做到這一點:

query.Select(a => new BLL.Driver.Driver() 
     { 
      id = a.Driver.id 
      etc 
     }).ToList(); 

所以填充DriverODSJoined的名單我想我會做這樣的事情:

query.Select(a => new BLL.Driver.DriverODSJoined() 
     { 
      driver.id = a.Driver.id, 
      licence.id = t2.id 
     }).ToList(); 

但它不起作用。我怎樣才能做到這一點,最終得到一個List,每個List都包含一個BLL.Driver和BLL.Licence對象的實例?

感謝, 理查德

+0

我太傻了,所有我需要做的是:名單列表= query.Select(A =>新DriverODSJoined(){ 司機 =新的驅動程序() { 地址1 = a.driver.address1 }, 校驗=新BLL.DVLA.Licence() { ID = a.licence.id } } ).ToList(); – Pixelstiltskin

+2

你應該發表你的評論作爲答案並接受它。這將有助於其他人遇到類似問題 – Aducci

+0

我試過但我必須等待7小時才能發佈,因此必須回到它。希望至少發表評論,以免浪費他們的時間來回答它! – Pixelstiltskin

回答

2

我想通了不久之後,當然我有自己的成員變量分配值之前實例包含對象中的每個對象。因此,這裏的例子:

List<DriverODSJoined> list = query.Select(a => new DriverODSJoined() 
{ 
    driver = new Driver() 
    { 
     address1 = a.driver.address1 
    }, 
    check = new BLL.DVLA.Licence() 
    { 
     id = a.licence.id 
    } 
}).ToList(); 
+0

也作爲更新,我發現當左連接的許可證爲空時,我不得不這樣做:'check = a.licence = null?新的BLL.DVLA.Licence():new BLL.DVLA.Licence(){id = a.licence.id}'當進程作爲id等許可證對象上的成員變量溢出時,它是非空的int – Pixelstiltskin