2016-04-14 53 views
0

我有這樣的LINQ查詢如何在Linq查詢中使用我的模型屬性?

var sales=db.Customers 
    .GroupBy 
    .Select(c=> new MyModel 
    { 
     count1=c.where(someCondition).Count(), 
     count2=c.where(otherCondition).Count(), 
     finalCount=count2-count1 
    }); 

是可能的LINQ? 我該如何解決這樣的問題?

+2

您必須提供的GroupBy子句。 – HimBromBeere

+0

你還沒有提到你的問題 –

+1

@HimBromBeere他沒有,但這個問題並不重要:它是關於'Select'子句的。 –

回答

1

你的代碼後屬性初始值設定:

var sales=db.Customers.GroupBy(...).Select(c => 
{ 
    var model new MyModel{ 
     count1=c.Count(), 
     count2=c.Count() 
    } 
    model.finalCount = model.count1 - model.count2 

    return model; 
}); 

但在這種情況下,我想只是c reate一個只讀屬性上爲MyModel類:

public class MyModel 
{ 
    public int FinalCount => count1 - count2; 
} 

然後初始化僅必填字段:

var sales=db.Customers.GroupBy(...).Select(c => new MyModel 
{ 
    count1=c.Count(), 
    count2=c.Count() 
}); 

FinalCount將自動爲您計算。

+1

有幫助,它真的幫助我 –

3

你可以先選擇你投射到第二Select匿名類型:

var sales = db.Customers 
    .GroupBy(...) 
    .Select(g => new 
    { 
     count1 = g.Where(condition).Count(), 
     count2 = g.Where(condition).Count() 
    }) 
    .Select{x => new MyModel 
    { 
     count1 = x.count1, 
     count2 = x.count2, 
     finalCount = x.count2 - x.count1 
    }); 
+0

EF無法處理鏈中的兩個「選擇」?否則我不明白'AsEnumerable'在這裏做什麼。 –

+1

@AlexZhukovskiy:一切都翻譯成SQL,對象的初始化不能轉換爲sql。 'AsEnumerable'執行查詢並用'Linq-To-Objects'完成對象初始化。因此,在使用'AsEnumerable'時過濾_before_是很好的,否則你會將整個表流入內存(或者'GroupBy'的結果是什麼)。 –

+0

@TimSchmelter,我認爲你的第二個查詢中不需要'AsEnumerable'。 EF支持在自定義類中進行項目查詢,比如'MyModel'也叫做DTO – octavioccl

4

沒有,但你可以使用匿名塊:如果我理解你正確剛剛地方

var sales=db.Customers.GroupBy(...).Select{c=> 
{ 
    int count1 = c.Count(condition1); 
    int count2 = c.Count(condition2); 

    return new MyModel{ 
     count1=count1, 
     count2=count2, 
     finalCount= count2 - count1 
    } 
}); 
+2

'db'告訴我OP在使用EF。如果是這樣的話,他不能使用你的選擇,因爲具有語句正文的lambda表達式不能轉換爲表達式樹 – octavioccl

1

你也可以做到這一點使用let條款:

var sales=from c in db.Customers 
      group c by c.SomeColumn into g 
      let Count1= =g.Count(someCondition) 
      let Count2=g.Count(otherCondition) 
      select new MyModel 
       { 
        count1=Count1, 
        count2=Count2, 
        finalCount=Count1-Count2 
       }; 

同樣的使用方法的語法:

var sales=db.Customers 
    .GroupBy(c=>c.SomeColumn) 
    .Select(g=>new 
    { 
     Count1=g.Count(someCondition), 
     Count2=g.Count(otherCondition) 
    }) 
    .Select(c=> new MyModel 
    { 
     count1=c.Count1, 
     count2=c.Count2, 
     finalCount=c.Count1-c.Count2 
    }); 
相關問題