2014-12-24 47 views
1

我有一個IQueryable列表,它有5個字段。其中4個來自DB。 第五個字段必須使用聯合聲明(其他幾個表中不包含引用該表的外鍵)從代碼中分配。c#linq - 基於集合的操作

查詢看起來像這樣。

Profile對下列字段進行分類。

Id, Name, Username, Email, Product 

產品字段不在數據庫中。必須使用以下查詢在C#代碼中進行填充。

var resultSet = (from a in Profiles 
        join _b_ in billingPeriodIncludes 
        on a.Id equals (int?) _b_._cbp.BundleId into b_ 
        from _b in b_.DefaultIfEmpty() 
        where a.Product != null 
        select new 
        { 
        a, 
        Product = (_b != null && _b._p != null) ? (_b._p) : a.Product 
        } 

該查詢爲我提供了配置文件和產品的組合。現在我遍歷每個配置文件並將每個產品分配給其配置文件。

有人可以幫我做產品配置文件的直接集合分配?

這樣的事情,(不工作)

var q1 = (from a in Profiles 
      join _b_ in billingPeriodIncludes 
      on a.Id equals (int?) _b_._cbp.BundleId into b_ 
      from _b in b_.DefaultIfEmpty() 
      select 
      //Assign products to the set. Query the set in a separate query. 
      a.Product = (_b != null && _b._p != null) ? (_b._p) : a.Product 
     ); 
var q2 = from _q2 in q1 select _q2; 
+1

這是不可能的。你這樣做的方式是可以的。 – opewix

回答

3

試試這個: -

var resultSet = (from a in Profiles 
       join _b_ in billingPeriodIncludes 
       on a.Id equals (int?) _b_._cbp.BundleId into b_ 
       from _b in b_.DefaultIfEmpty() 
       where a.Product != null 
       select new Profiles 
       { 
        Id = a.Id, 
        Name = a.Name, 
        Username = a.Username, 
        Email = a.Email, 
        Product = (_b != null && _b._p != null) ? (_b._p) : a.Product 
       }; 

您可以直接綁定Profiles對象,而不是anonymous類型。

+0

雖然這可行,但Profiles類可能會增加列。如果添加了新列,它可能會在這裏錯過。 – Raghav

+0

@Raghav - 如果'Profiles'類會增長,它將在查詢中可用,對嗎?因爲我們只加入'Profiles'類型。所以你說的是不正確的。 –

+0

你右拉胡爾。但是檔案類被廣泛使用。添加新列時,應在此處指定列的值。如果它錯過了,它會導致默認列爲空。查詢是完美的,我只是在select部分尋找類似「select * from from」的東西。 – Raghav